我是异步新手。尝试创建一个异步装饰器来阻塞 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添加到 sanicfunction_name定义并在调用之前等待sleeper(),但没有成功。我知道 sanic 可以与 asyncio 一起使用,这对此有帮助吗?有什么修复或解决方法吗?
九州编程
相关分类