6

I'm trying to access user but getting an error when the view is async.

Code:

from django.http import JsonResponse


async def archive(request):
    user = request.user
    return JsonResponse({'msg': 'success'})

error message:

django.myproject.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

What I tried:

from django.http import JsonResponse
from asgiref.sync import sync_to_async


async def archive(request):
    # user = sync_to_async(request.user)
    # user = sync_to_async(request.user)()
    # user = await sync_to_async(request.user)
    user = await sync_to_async(request.user)()
    return JsonResponse({'msg': 'success'})

Still getting the same error.

I want to access the user to check he/she has permission to archive a file.

EDIT: I eventually figured out that I had to move it into a temporary method and run that as sync_to_async. I did this below:

def _check_user(request):
    user = request.user
    ''' Logic here '''
    return

async def archive(request):
    await sync_to_async(_check_user, thread_sensitive=True)(request=request)
    ''' Logic here '''

And this seems to work, But not sure if this is the correct way of doing it?

1 Answer 1

3

Try this:

from django.http import JsonResponse
from asgiref.sync import async_to_sync, sync_to_async

@sync_to_async
def archive(request):
    user = request.user
    return JsonResponse({'msg': 'success'})

I don't know if it's really async, I'm trying to fix this problem too.


I've found something: https://www.valentinog.com/blog/django-q/

If the first option not work, see this link.

1
  • thank you the first option worked out nicely for what I needed to do Mar 23, 2021 at 8:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.