我试图通过 Flask 方法调用阻塞函数,但需要几秒钟,所以我想我可以做一些异步调用来加快速度,但它没有按预期工作。显然使用 asyncio 我不能只是在后台启动一个协程而不等待执行结束,也许我需要使用线程?或者使用 grequest 因为我的阻塞功能正在使用请求...
到目前为止,这是我的代码:
@app.route("/ressource", methods=["GET"])
def get_ressource():
do_stuff()
return make_response("OK",200)
def do_stuff():
# Some stuff
fetch_ressource()
async def fetch_ressource():
return await blocking_function()
def blocking_function():
# Take 2-3 seconds
result = request.get('path/to/remote/ressource')
put_in_database(result)
Run Code Online (Sandbox Code Playgroud)
我听说过 Celeri,但对于只有一个功能来说似乎有点矫枉过正。