【问题标题】:Notify progress with flask [duplicate]用烧瓶通知进度[重复]
【发布时间】: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))) 

【问题讨论】:

    标签: python flask


    【解决方案1】:

    您所说的“临时通知而不是响应”是什么意思?

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

    1. 用户开始一项长时间的计算密集型任务

    2. 任务已启动并指定 ID

    3. 服务器返回:“任务已启动”和 ID

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

    【讨论】:

      猜你喜欢
      • 2019-03-25
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多