繁体   English   中英

从 Sanic 函数调用抛出“无法从正在运行的事件循环中调用 asyncio.run()”

[英]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()调用之前等待,但没有运气。 我知道 sanic 可以与 asyncio 一起使用,这是否与此有关? 任何修复或解决方法?

无需在asyncio.run内部调用 asyncio.run。

@app.route("/v0/xxxxxxxxxxxxxxx", methods=['POST'])
async def function_name(request):
    await call_to_some_coroutine()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM