在flask中使用
import asyncio
.....
loop = asyncio.get_event_loop()
....
發(fā)現(xiàn)報錯
RuntimeError: There is no current event loop in thread 'Thread-2'.
修改為
import asyncio
...
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
loop = asyncio.get_event_loop()
原因:
# 源碼
def get_event_loop(self):
"""Get the event loop.
This may be None or an instance of EventLoop.
"""
if (self._local._loop is None and
not self._local._set_called and
isinstance(threading.current_thread(), threading._MainThread)):
self.set_event_loop(self.new_event_loop())
if self._local._loop is None:
raise RuntimeError('There is no current event loop in thread %r.'
% threading.current_thread().name)
return self._local._loop
在主線程中,調(diào)用get_event_loop總能返回屬于主線程的event loop對象,如果是處于非主線程中,還需要調(diào)用set_event_loop方法指定一個event loop對象,這樣get_event_loop才會獲取到被標記的event loop對象:
def set_event_loop(self, loop):
"""Set the event loop."""
self._local._set_called = True
assert loop is None or isinstance(loop, AbstractEventLoop)
self._local._loop = loop
參考
由于Flask工作流程:
如果啟動app時將threaded參數(shù)設(shè)定為True,flask才會以多線程的方式去處理每一個請求,
否則,所有請求是在一個工作線程(非主線程)運行。具體。此時與直接命令行運行腳本不同,請留意。