在flask视图中,我通过api调用接收数据,这些数据必须传递给外部api,而外部api有时非常慢。
所以我希望视图在异步处理请求时返回一个正状态代码。
我尝试过期货请求,但回拨有困难:
def bg_cb(sess, resp):
print(resp.text)
@app.route('/incomingdata', methods=['POST',])
def clients():
(... process incoming POST data and create outgoing API call. here I inserted a demo call to httpbin.org that simulates a very slow API ...)
from requests_futures.sessions import FuturesSession
session = FuturesSession()
future = session.get('http://httpbin.org/delay/3', background_callback=bg_cb)
response = future.result()
return jsonify({'status': 'ok'}), 200
不幸的是,上面的代码将等待返回,直到回调被处理。这是3秒。
如何才能得到这样的结果:视图立即返回200的响应,3秒后调用回调函数。
提前谢谢你!