从 Sanic 函数调用抛出 "asyncio.run() cannot be called from a running event loop"
Called from Sanic functions throws "asyncio.run() cannot be called from a running event loop"
我是 asyncio 的新手。试图创建一个用于阻塞 I/O 代码的异步装饰器。
def singletonAsyncMaker(func):
async def inner(obj, ):
loop = asyncio.get_event_loop()
tasks = (loop.run_in_executor(None, func, i) for i in obj)
return await asyncio.gather(*tasks)
def main(obj):
return asyncio.run(inner(obj))
return main
@singletonAsyncMaker
def sleeper(obj):
sleep(2)
return obj
x = sleeper([8, 5, 6, 6, 4645, 63, 4, 6, 1, 64, 614, 24, 65, ])
print(x)
这在正常情况下以及在正常的非异步函数中都运行良好,但是当通过 Sanic 服务器的路由函数调用时它会抛出此错误。
Traceback (most recent call last):
File "/app.py", line 99, in extractImageResponse
result = perform_textract_bytestream(images)
File "async_experiment.py", line 51, in main
return asyncio.run(inner(obj))
File "env/lib/python3.8/asyncio/runners.py", line 33, in run
raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
@app.route("/v0/xxxxxxxxxxxxxxx", methods=['POST'])
def function_name(request):
-----------------
x = sleeper(list)
-----------------
return jsonify(json_op)
尝试将 async 添加到 sanic function_name
定义中,并在 sleeper()
调用之前添加 await 但没有成功。
我知道 sanic 与 asyncio 一起工作,这是否有助于此?
任何修复或解决方法?
无需在 Sanic 内部调用 asyncio.run
。
@app.route("/v0/xxxxxxxxxxxxxxx", methods=['POST'])
async def function_name(request):
await call_to_some_coroutine()
我是 asyncio 的新手。试图创建一个用于阻塞 I/O 代码的异步装饰器。
def singletonAsyncMaker(func):
async def inner(obj, ):
loop = asyncio.get_event_loop()
tasks = (loop.run_in_executor(None, func, i) for i in obj)
return await asyncio.gather(*tasks)
def main(obj):
return asyncio.run(inner(obj))
return main
@singletonAsyncMaker
def sleeper(obj):
sleep(2)
return obj
x = sleeper([8, 5, 6, 6, 4645, 63, 4, 6, 1, 64, 614, 24, 65, ])
print(x)
这在正常情况下以及在正常的非异步函数中都运行良好,但是当通过 Sanic 服务器的路由函数调用时它会抛出此错误。
Traceback (most recent call last):
File "/app.py", line 99, in extractImageResponse
result = perform_textract_bytestream(images)
File "async_experiment.py", line 51, in main
return asyncio.run(inner(obj))
File "env/lib/python3.8/asyncio/runners.py", line 33, in run
raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
@app.route("/v0/xxxxxxxxxxxxxxx", methods=['POST'])
def function_name(request):
-----------------
x = sleeper(list)
-----------------
return jsonify(json_op)
尝试将 async 添加到 sanic function_name
定义中,并在 sleeper()
调用之前添加 await 但没有成功。
我知道 sanic 与 asyncio 一起工作,这是否有助于此?
任何修复或解决方法?
无需在 Sanic 内部调用 asyncio.run
。
@app.route("/v0/xxxxxxxxxxxxxxx", methods=['POST'])
async def function_name(request):
await call_to_some_coroutine()