小编典典

在Flask中执行耗时的功能时显示“正在加载”消息

flask

我对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>

任何帮助将不胜感激,我希望这个例子会有所帮助。


阅读 1672

收藏
2020-04-05

共1个答案

小编典典

将此添加到你的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;
    }

然后更改你的提交按钮以调用上面的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加载新页面为止。

2020-04-05