【问题标题】:How do I access user in Django Async view?如何在 Django Async 视图中访问用户?
【发布时间】:2021-03-19 22:38:22
【问题描述】:

我正在尝试访问用户,但当视图为 async 时出现错误。

代码:

from django.http import JsonResponse


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

错误信息:

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

我尝试了什么:

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'})

仍然遇到同样的错误。

我想访问用户以检查他/她是否有权归档文件。

编辑: 我最终发现我必须将它移动到一个临时方法中并以sync_to_async 运行它。我在下面做了这个:

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 '''

这似乎有效,但不确定这是否是正确的做法?

【问题讨论】:

    标签: python-3.x django async-await


    【解决方案1】:

    试试这个:

    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'})
    

    不知道是不是真的异步,我也在努力解决这个问题。


    我发现了一些东西:https://www.valentinog.com/blog/django-q/

    如果第一个选项不起作用,请参阅此链接。

    【讨论】:

    • 谢谢第一个选项非常适合我需要做的事情
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 2021-04-27
    • 2021-05-16
    • 2017-07-28
    • 2016-12-20
    相关资源
    最近更新 更多