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

问题描述 投票:0回答:5

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

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

python html flask loading
5个回答
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();">

并将加载和内容 div 添加到您的基本 html 文件中:

<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
投票

这可以通过使用包含“加载 gif”图像的

div
来完成。单击提交按钮时,将使用 javascript 显示 div。 要实现这一点,你可以看看这个网站:如何使用 javascript 和 Css 在页面加载时显示正在加载的 gif 图像


14
投票

我发现纯粹依赖 CSS 的加载器非常有用。它不依赖外部资源:

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


3
投票

这是一个有点老的话题了,但我今天需要处理这个问题并自己想出了一个解决方案。我正在运行一个机器学习模型,该模型接收用户输入的图像并执行一些魔法。

基本上这就是我所做的。

在我的index.html文件上,我在“提交”按钮上调用了一个加载函数并传递文件名,因为我稍后要使用它:

<form method="post" action="/loading/{{filename}}" 
enctype="multipart/form-data">
    <input type="submit" value="Submit!">
</form>

在 Flask 上,我创建了一条路由,只是为了在执行耗时的任务之前渲染加载屏幕,同时还传递文件名:

@app.route('/loading/<filename>', methods=['POST'])
def loading_model(filename):
    return render_template ("loading.html", filename=filename)

然后,在loading.html 上,我渲染 .gif 动画,最后将页面重定向到耗时的任务函数:

<!doctype html>
<head>
    <link rel= "stylesheet" type= "text/css" href= "{{url_for('static',filename='styles/main.css') }}">
</head>

<div id="preloader">
    <div id="status">&nbsp</div>
    <h1 class="ml13">ANALYZING...</h1>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js> </script>
</div>

<title>Title</title>

<script src="{{url_for('static', filename='main.js')}}"></script>

<script> window.location.replace('/task/{{filename}}'); </script>

然后,最后一步,回到 Flask,调用任务函数:

@app.route('/task/<filename>', methods=['POST', 'GET'])
def task(filename):
    # Do your stuff
return render_template ("results.html")

通过这样做,gif 动画将在函数执行其工作时继续播放,然后渲染结果或您想要的下一页。

您显然必须编辑 css 文件,以便“预加载器”和“状态”表现得像您希望的那样,这就是我使用它的方式:

#preloader {
    background-color: white;
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

#status {
    background-image: url("lalala.gif");
    background-repeat: no-repeat;
    width: 800px;
    height: 600px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -400px;
    margin-left: -400px;
}

这对我来说很有效。


0
投票

很棒的@jka.ne,但情况令人困惑。

我只需要在点击按钮时介绍加载gif。

我的解决方案是:

<script type="text/javascript">
function loading(){
  $("#loading").show();
  window.location.href="../target_html";     
}
</script>

然后:

<button type="button" class="xxx"  onclick="loading();">Run</button>

最后:

<div id="loading"></div>
© www.soinside.com 2019 - 2024. All rights reserved.