本文介绍了Django:SynchronousOnlyOperation:您不能从异步上下文中调用它-使用线程或sync_to_async的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用运行 shell_plus --notebook 的Django 3.0.6和Jupyter笔记本.

I use Django 3.0.6 and Jupyter notebook running with shell_plus --notebook.

我尝试运行queryset:

I try run queryset:

User.objects.all()

但是返回此错误 SynchronousOnlyOperation:您不能从异步上下文中调用它-使用线程或sync_to_async .

我尝试此命令

from asgiref.sync import sync_to_async

users = sync_to_async(User.objects.all())

for user in users:
    print(user)

TypeError: 'SyncToAsync' object is not iterable

Django文档的解决方案

The solution of Django documentation

os.environ ["DJANGO_ALLOW_ASYNC_UNSAFE"] ="true" 是唯一的解决方案吗?

os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" in settings.py is the unique solution?

推荐答案

sync_to_async 可调用,而不可调用.相反,您需要这样做:

sync_to_async takes a callable, not the result. Instead, you want this:

from asgiref.sync import sync_to_async

users = sync_to_async(User.objects.all)()

for user in users:
    print(user)

您还可以将要包装的呼叫放在经过修饰的函数中:

You can also put the call(s) you want to wrap in a decorated function:

from asgiref.sync import sync_to_async

@sync_to_async
def get_all_users():
    return User.objects.all()

for user in await get_all_users():
    print(user)

请注意,必须在异步上下文中使用它,因此完整示例如下:

Note that this must be used from an async context, so a full example would look like:

from asgiref.sync import sync_to_async

@sync_to_async
def get_all_users():
    return User.objects.all()

async def foo(request):
    for user in await get_all_users():
        print(user)

完整文档

这篇关于Django:SynchronousOnlyOperation:您不能从异步上下文中调用它-使用线程或sync_to_async的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 23:18