如何在 Django 异步视图中访问用户?

问题描述 投票:0回答:3

我正在尝试访问用户,但当视图为

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
3个回答
3
投票

试试这个:

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/

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


2
投票

从异步视图访问

user
的正确方法是:

from asgiref.sync import sync_to_async

from django.contrib import auth

async def myview(request):
    user = await sync_to_async(auth.get_user)(request)

Django 5.0 将向 .auser

 对象添加 
request
 方法


0
投票

Django 5.0 开始,您可以使用

aget_user
模块中的
auth

from django.contrib.auth import aget_user

async def archive(request):
    user = await aget_user(request)
    return JsonResponse({'msg': 'success'})
© www.soinside.com 2019 - 2024. All rights reserved.