我试图通过Flask方法调用一个阻塞函数,但这需要几秒钟的时间,所以我想我可以做一些异步调用来加快速度,但它并不像预期的那样工作。显然,使用asyncio,我不能只在后台启动协程,而不是等待执行结束,也许我需要使用线程?或者使用grequest,因为我的阻塞函数是使用request...
到目前为止,我的代码如下:
@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)我听说过Celeri,但它似乎只有一个功能有点过头了。
发布于 2019-04-06 15:15:53
现在回答有点晚了,但我对此很感兴趣。
我通过包装函数并通过asyncio.run()调用它来管理它,但我不知道多个asyncio.run()调用是否是一件好事。
from functools import wraps
from flask import Flask
import asyncio
def async_action(f):
@wraps(f)
def wrapped(*args, **kwargs):
return asyncio.run(f(*args, **kwargs))
return wrapped
app = Flask(__name__)
@app.route('/')
@async_action
async def index():
await asyncio.sleep(2)
return 'Hello world !'
app.run()发布于 2018-06-22 04:56:27
您可以使用Quart和AIOHTTP来实现这一点,这些代码应该对给定的Flask代码非常熟悉。
@app.route("/ressource", methods=["POST"])
async def get_ressource():
asyncio.ensure_future(blocking_function())
return await make_response("OK", 202)
async def blocking_function():
async with aiohttp.ClientSession() as session:
async with session.get('path/to/remote/ressource') as resp:
result = await resp.text()
await put_in_database(result)注意:我已经将它更改为POST路由,因为它做了一些事情,并且我返回了一个202响应,表明它已经触发了处理。
如果您希望继续使用Flask,我建议您使用eventlet,并使用不包含async或await的spawn(blocking_function)。
还请注意,我是Quart的作者。
发布于 2018-06-20 15:37:03
阻塞函数在做什么?
使用grequest可行吗?
import grequests
@app.route('/do', methods = ['POST'])
def do():
result = grequests.map([grequests.get('slow api')])
return result[0].contenthttps://stackoverflow.com/questions/50942422
复制相似问题