python-3.xdjangoasync-await

How do I access user in Django Async view?


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?


Solution

  • 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.