我对 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>
任何帮助将不胜感激,我希望这个例子有所帮助。
最佳答案
将此添加到您的 index.html 或 js 文件中(我假设您在这里有 jQuery,当然您可以使用标准 javascript。):
<script type="text/javascript">// <![CDATA[
function loading(){
$("#loading").show();
$("#content").hide();
}
// ]]></script>
将此添加到您的 html 或 css 文件中:
div#loading {
width: 35px;
height: 35px;
display: none;
background: url(/static/loadingimage.gif) no-repeat;
cursor: wait;
}
您可以从 http://www.ajaxload.info/ 获得足够的 GIF。 .下载并将其放入您的静态文件夹中。
然后改变你的提交按钮调用上面的js函数:
<input type="submit" name="anything_submit" value="Submit" onclick="loading();">
并在基础 html 文件中添加加载和内容 div:
<body>
<div id="loading"></div>
<div id="content">
<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" onclick="loading();">
</form>
</p>
</div>
</body>
现在,当您单击“提交”时,js 函数应该隐藏您的内容并显示加载 GIF。这将一直显示,直到您的数据被处理并且 flask 加载新页面。
关于python - 在 Flask 中执行耗时函数时显示 ‘loading’ 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14525029/