Javascript 使用flask提供从python到HTML的多个更新

Javascript 使用flask提供从python到HTML的多个更新,javascript,python,html,flask,Javascript,Python,Html,Flask,我正在尝试为我的python程序构建一个基于web的用户界面。为此,我希望将dataFrameFinal的实时更新发送到html页面,但在Flask中,我只能在每次提交表单时发送一次更新 目前在my main.py中,我有这个函数 @app.route('/process', methods=['POST']) def process(): # gets the number of sims from the form on submit numSims = int(reque

我正在尝试为我的python程序构建一个基于web的用户界面。为此,我希望将dataFrameFinal的实时更新发送到html页面,但在Flask中,我只能在每次提交表单时发送一次更新

目前在my main.py中,我有这个函数

@app.route('/process', methods=['POST'])
def process():

    # gets the number of sims from the form on submit
    numSims = int(request.form['numSims'])

    dataFrameFinal = runSims(num_sims=numSims)

    return jsonify({'dataframe' : dataFrameFinal .reset_index().to_html()})
这将获得表单提交时的SIM数(NUMSIM),并在所有模拟运行到javascript文件后返回表,该文件将结果加载到html页面

然而,由于我正在运行超过10000个模拟人生(运行可能需要10分钟以上),我希望发送dataFrameFinal的实时版本(例如每10个模拟人生发送一次html页面更新)。如果您能给我一些建议,我将不胜感激

对不起,如果这是一个基本的问题,我对这个很陌生,找不到任何其他类似的帖子,所以我想我会问。提前感谢。

使用任务管理器。 这是一个广泛使用的选择,尽管还有其他选择

使用芹菜可以从view函数启动异步(或后台)任务/进程。然后,视图可以将响应返回给用户(这样用户就不必等待所有处理完成后才能看到响应)

芹菜需要一个消息代理来启动任务和返回结果。()您还可以使用此代理存储进度更新

例如,如果您正在使用Redis,当
runSims()
处理了100个SIM时,您可以在Redis中存储类似
processed:100
的内容。然后,您可以编写一个Flask view函数,从Redis中读取该值并将其返回给用户。实时更新页面的一个选项是在页面上有一些Javascript,每秒调用Flask view函数。Flask view函数将读取当前存储在Redis中的任何数字(芹菜任务/进程应该更新该数字),并将其返回到Javascript,以便更新页面上的某些字段

您的流程函数最终将如下所示:

@app.route('/process', methods=['POST'])
def process():

    # gets the number of sims from the form on submit
    numSims = int(request.form['numSims'])

    # Start the celery task
    runSims.apply_async(num_sims=numSims)

    # Let the user know that processing has started
    return 'Your task has started processing. Stay on the page for live updates.'
import redis

r = redis.StrictRedis()

@app.route('/progress', methods=['GET'])
def progress():
    return r.get('processed')
您的
get\u progress()
函数可能如下所示:

@app.route('/process', methods=['POST'])
def process():

    # gets the number of sims from the form on submit
    numSims = int(request.form['numSims'])

    # Start the celery task
    runSims.apply_async(num_sims=numSims)

    # Let the user know that processing has started
    return 'Your task has started processing. Stay on the page for live updates.'
import redis

r = redis.StrictRedis()

@app.route('/progress', methods=['GET'])
def progress():
    return r.get('processed')