python-3.x - 使用 Flask 更新进度条

标签 python-3.x flask progress-bar

我正在尝试获取要更新的进度条 - 我尝试在此处实现代码 here围绕我的下面的代码,但无法让它工作。当我运行代码时,进度条出现但不更新。

我还检查了其他答案,但仍然不知道如何让它发挥作用。如果有人可以帮助解决这个问题,我将非常感激。

服务器.py

def create_app():
    app = Flask(__name__)

     app.add_url_rule("/", view_func=views.home_page)

    app.add_url_rule("/display", view_func=views.display_page)
    app.add_url_rule("/display_progress", methods=['GET', 'POST'], 
view_func=views.progress) 

return app

View .py

def display_page():      
    return send_file("templates/display.html")


def progress():
    def generate():
        x = 0
        while x <= 100:
            print(x)
            x = x + 10
            time.sleep(0.2)
            yield "data:" + str(x) +"\n\n"
     return Response(generate(), mimetype='text/event-stream')

显示.html

<html lang="en">
<head>
    <title>Display Update</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="/static/bootstrap.css"></link>
    <script src="/static/jquery.js"></script>
    <script src="/static/bootstrap.js"></script>
    <script src="/static/websocket.js"></script>

    <script>
    var source = new EventSource("/display_progress");
    source.onmessage = function(event) {
        $('.progress-bar').css('width', event.data + '%').attr('aria- 
   valuenow', event.data);
    }
    </script>

</head>

<body>
        <h3>Update DTS Displays</h3>
        <div class="progress" style="width: 750px; height: 22px; margin: 
10px;">
            <div class="progress-bar progress-bar-striped active" 
role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" 
style="width: 0%">
                <span class="progress-bar-label">0%</span>
            </div>

        </div>
        <button type="submit" class="btn btn-default" formaction="{{ 
url_for('progress') }}">Progress Bar</button>

</body>
</html>

最佳答案

display.html 中更新您的脚本标记:

<script>
        var source = new EventSource("/display_progress");
        source.onmessage = function (event) {
            $('.progress-bar').css('width', event.data + '%').attr('aria-valuenow',event.data);
            $('.progress-bar-label').text(event.data + '%');
            if (event.data == 100) {
                source.close()
            }
    }
</script>

关于python-3.x - 使用 Flask 更新进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56969980/

相关文章:

python - 使用 pandas.join 加入 datetime64[ns, UTC] 失败

python-3.x - --reload 标志不应在 Windows 的生产中使用。 Uvicorn 服务器警告

python - 无法获取字符串的 sha256 哈希

python - 为什么不在每次 Flask 启动时都生成 key ?

python - 第一次追加后,append_entry() 不起作用。我将 Fieldlist 与 Flask-wtf、jinja 和 Python 3.4 一起使用

c# - Web 浏览器控件的进度条

html - 如何将缓冲区时间范围数据从 HTML5 视频播放器引用映射到进度条?

python - 如何在 Python 中打印我的对象名称

python - 下载使用 mongodump 创建的存档

javascript - 在 HTML 中单击按钮后如何将进度条(使用 Ladda)与按钮绑定(bind)?