我对 Flask 还是比较陌生,总的来说有点网络菜鸟,但到目前为止我已经取得了一些不错的成绩。现在我有一个表单,用户可以在其中输入一个查询,该查询被提供给一个函数,该函数可能需要 5 到 30 秒才能返回结果(使用 Freebase API 查找数据)。
问题是我不能让用户知道他们的查询在这段时间内正在加载,因为结果页面只会在函数完成其工作后加载。有没有办法在进行时显示加载消息?我发现一些 Javascript 可以在页面元素仍在加载时显示加载消息,但我的等待时间发生在“render_template”之前。
我整理了一些示例代码,只是为了演示我的情况:
Python:
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()
摘自 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">
</form>
</p>
</body>
摘自 done.html:
<body>
<h3>Results:</h3>
<p>
{{ display }}
</p>
</body>
任何帮助将不胜感激,我希望这个例子有所帮助。
原文由 jrmedd 发布,翻译遵循 CC BY-SA 4.0 许可协议
这可以通过使用包含“正在加载 gif”图像的
div
来完成。单击提交按钮时,将使用 javascript 显示 div。要实现这个,你可以看看这个网站:http://web.archive.org/web/20181023063601/http: //www.netavatar.co.in/2011/05/31/how-to-show -a-loading-gif-image-while-a-page-loads-using-javascript-and-css/