【发布时间】:2021-10-27 14:28:12
【问题描述】:
我有两个 Django 视图,
def view_that_accesses_orm(request): # say end point /useorm
user = User.objects.first()
...
和
def view_that_creates_event_loop(request): # say endpoint /createloop
client = AsycProvider()
... # do stuff with client
AsyncProvider 类似于
class AsyncProvider:
def __init__(self):
try:
self.__loop = asyncio.get_event_loop()
except RuntimeError as e:
print(e) #no running event loop
self.__loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.__loop)
self.__session = aiohttp.ClientSession(loop=self.__loop)
... # other operations with asyncio.run_until_complete, asyncio.gather, and self.__session
现在的问题是,如果我在 uWSGI 中有 1 个进程和 2 个线程。然后他们将以循环方式处理请求。
所以场景是:
- 用户点击
/createloop(给定线程1) - 用户点击
/useorm(给定线程2) - 用户再次点击
/useorm(给定线程1)
现在在第三种情况下,有时事件循环正在运行,由于 Django 3.x 检测到正在运行的事件循环并不允许我们访问 ORM,我得到了 django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. 异常。
我不确定事件循环如何不停止并在线程中持续存在。
请解释这究竟是什么原因以及应该如何解决?
【问题讨论】:
标签: python django python-asyncio uwsgi