我正在尝试访问用户,但当视图为
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 '''
这似乎有效,但不确定这是否是正确的方法?
试试这个:
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/
如果第一个选项不起作用,请参阅此链接。
从 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'})