Dee*_*eyi 5 django orm python-3.x python-asyncio django-3.0
[设置]我使用 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)
Run Code Online (Sandbox Code Playgroud)
我不确定我做错了什么。据我了解Django's doc建议我应该能够在单独的线程中运行同步任务(如 ORM 查询),但这仍然不起作用。
有趣的是,使用本地运行代码manage.py runserver工作正常,但是使用 `gunicorn --bind 127.0.0.1:8000 src.config.wsgi:application 运行它会抛出上述异常。