gpt4 book ai didi

asynchronous - Django : SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async

转载 作者:行者123 更新时间:2023-12-04 11:08:33 39 4
gpt4 key购买 nike

我使用 Django 3.0.6 和 Jupyter notebook 运行 shell_plus --notebook .

我尝试运行查询集:
User.objects.all()
但是返回这个错误SynchronousOnlyOperation: You cannot call this from an async context - use a thread or 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文档的解决方案
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"在 settings.py 中是唯一的解决方案吗?

最佳答案

sync_to_async需要一个可调用的,而不是结果。相反,你想要这个:

from asgiref.sync import sync_to_async

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

for user in users:
print(user)

您还可以将要包装的调用放入装饰函数中:

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)

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

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)

Full documentation

关于asynchronous - Django : SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61926359/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com