【发布时间】: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