[设置]我使用 Django 3.0 作为wsgi
应用程序。
我需要从视图中运行协程(如下所示)。这在事件循环中运行asyncio
。从这个事件循环/协程中,我需要使用 Django 的 ORM 获取数据库中的一些对象,但是 django 抛出以下异常:
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async
import asyncio
import concurrent
def get_users_from_db():
return User.objects.all()
async def do_some_async_stuff():
executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
loop = asyncio.get_event_loop()
attachments = await loop.run_in_executor(executor, get_users_from_db)
def view(request):
task = LOOP.create_task(do_some_async_stuff)
result = not LOOP.is_running() and LOOP.run_until_complete(task)
我不确定我做错了什么。据我了解Django 的文档建议我应该能够在单独的线程中运行同步任务(如 ORM 查询),但这仍然不起作用。
有趣的是,使用本地运行代码可以manage.py runserver
正常工作,但是使用 `gunicorn --bind 127.0.0.1:8000 src.config.wsgi:application 运行它会引发上述异常。