用烧瓶通知进度

时间:2018-10-24 09:42:01

标签: python flask

我创建了带有两条路线的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))) 

1 个答案:

答案 0 :(得分:0)

这个“临时通知而不是响应”是什么意思?

我认为,应遵循以下方法:

  1. 用户启动了一项耗时长的计算任务

  2. 任务已启动并获得了ID

  3. 服务器返回:“任务已开始”和ID

  4. 用户使用任务ID发送AJAX请求以获取任务的进度状态

相关问题