小编jrm*_*edd的帖子

在Flask中执行耗时功能时显示"加载"消息

我对Flask来说还是比较新的,一般来说还是一个网络菜鸟,但到目前为止我已经取得了一些好成绩.现在我有一个用户输入查询的表单,该表单被赋予一个函数,该函数可能需要5到30秒才能返回结果(使用Freebase API查找数据).

问题是我不能让用户知道他们的查询在这段时间内正在加载,因为只有在函数完成其工作后才会加载结果页面.有没有办法在正在进行时显示加载消息?我发现一些Javascript可以在页面元素仍然加载时显示加载消息,但我的等待时间发生在'render_template'之前.

我把一些示例代码拼凑在一起,只是为了证明我的情况:

蟒蛇:

from flask import Flask
from flask import request
from flask import render_template
import time

app = Flask(__name__)

def long_load(typeback):
    time.sleep(5) #just simulating the waiting period
    return "You typed: %s" % typeback

@app.route('/')
def home():
    return render_template("index.html")

@app.route('/', methods=['POST'])
def form(display=None):
    query = request.form['anything']
    outcome = long_load(query)
    return render_template("done.html", display=outcome)

if __name__ == '__main__':
    #app.debug = True
    app.run()
Run Code Online (Sandbox Code Playgroud)

摘自index.html:

<body>
    <h3>Type anything:</h3>
    <p>
    <form action="." method="POST">
        <input type="text" name="anything" placeholder="Type anything here">
        <input type="submit" name="anything_submit" value="Submit"> …
Run Code Online (Sandbox Code Playgroud)

html python loading flask

33
推荐指数
3
解决办法
3万
查看次数

标签 统计

flask ×1

html ×1

loading ×1

python ×1