【发布时间】:2019-03-28 16:19:07
【问题描述】:
我创建了一个带有几个路由的 Flask 环境(参见下面的代码)。
我知道当用户向该路由发送 POST 请求时如何返回响应。但是,由于我期望计算密集型任务,我希望让用户了解进度。如何发送带有一些参数的进度通知(临时通知而不是响应)?
# libraries
import os
from flask import Flask, Response, request, json, url_for
from flask_cors import CORS, cross_origin
import time
# custom libraries
import test
# CORS
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
# ------------------------------------------------------------------------------
#
# API ROUTES
#
# ------------------------------------------------------------------------------
@app.route('/')
@cross_origin()
def api_root():
return 'The server is up and running if you see this message'
@app.route('/newreport', methods = ['POST'])
@cross_origin()
def api_run():
# Init
resp = {
'success': True,
'status': 200
}
if request.environ is not None:
print(request.environ)
# ---- 0
# Body attributes
specs = request.json.get('specs', None)
if not specs:
print('/0')
resp = {
'success': False,
'status': 400,
'message': "Oops... something went wrong",
'error': "Missing attribute specs"
}
# ---- 1
# Import and prepare the data
if resp.get('success', None) == True:
print('/1')
resp = test.randomfunction(specs)
# <-- REST response to client
print(resp)
if resp.get('success', None) == True:
print('/success')
respdata = resp.get('data')
js = json.dumps(respdata)
resp = Response(js, status=200, mimetype='application/json')
else:
print('/fail')
respdata = resp
js = json.dumps(respdata)
resp = Response(js, status=resp.get('status', 400), mimetype='application/json')
return resp
# ------------------------------------------------------------------------------
# Run the Routes and Application
app.run(host=os.getenv('IP', '0.0.0.0'),port=int(os.getenv('PORT', 8080)))
【问题讨论】: