在Flask中执行耗时函数时显示“加载”消息

63 投票
5 回答
96368 浏览
提问于 2025-04-17 13:39

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

任何帮助都非常感谢,希望这个例子能有所帮助。

相关问题:

5 个回答

14

我发现这个完全依赖CSS的加载动画非常有用。它不需要任何外部资源:

https://www.w3schools.com/howto/howto_css_loader.asp

在这里输入图片描述

57

把下面的内容加到你的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加载新页面。

20

这个可以通过使用一个包含“加载动图”的 div 来实现。当你点击提交按钮时,使用JavaScript来显示这个div。想要了解具体怎么做,可以看看这个网站:如何在页面加载时显示加载动图,使用JavaScript和CSS

撰写回答