我正在尝试获取要更新的进度条 - 我尝试在此处实现代码 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/