python - 如何从线程获取异步更新到烧瓶应用程序?
问题描述
我有一个烧瓶应用程序启动几个并行线程。每个线程开始一个耗时的测量。到目前为止,我可以启动所有线程并等待它们完成,然后再更新页面。
应用程序.py:
import time
import threading
import random
from flask import render_template
class AsynchronWorker(threading.Thread):
def __init__(self, tc_name):
threading.Thread.__init__(self)
self.tc_name = tc_name
self.duration = 0
def get_tc_name(self):
return self.tc_name
def get_duration(self):
return self.duration
def run(self):
start_time = time.time_ns()
time.sleep(random.randint(1, 5))
self.duration = time.time_ns() - start_time
app = Flask(__name__)
test_cases = {"Upload": 0, "Download": 0}
@app.route("/")
def index():
return render_template(template_name_or_list="index.html",
test_cases=test_cases)
@app.route("/start")
def start():
threads = []
results = {}
for tc in test_cases:
thread = AsynchronWorker(tc_name=tc)
threads += [thread]
thread.start()
for x in threads:
x.join()
results[x.get_tc_name()] = x.get_duration()
return render_template(template_name_or_list="index.html",
test_cases=results)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5005, debug=True)
索引.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form>
{% for name in test_cases.keys() %}
<h2> {{ name }} run for {{ test_cases[name] }} ns.</h2>
{% endfor %}
<a href="/start"><input type="button" name="start" value="Start"></a>
</form>
</body>
</html>
我正在寻找的是一个解决方案,每次线程完成时页面都会更新。到目前为止,我只发现了一些使用 ajax 或 socketIO 的过时示例。但他们都没有为我工作。
解决方案
推荐阅读
- vb.net - 禁用然后启用后日期时间选择器显示错误
- rust - 不能使用 insert() 方法
- rust - 通过暂时假装它是“静态”来伪造引用的最安全方法是什么?
- gridview - 如何自定义yii2 gridview过滤行?
- php - Laravel - 方法 Illuminate\\Support\\Collection::makeHidden 不存在
- scala - 使用akka和node js env每30秒后出现503错误
- kubernetes - 如何限制kafka服务器内存?
- firebase - React-Native + Apple 登录 + Firestore:权限被拒绝
- javascript - textarea中活动线的线条颜色
- java - 使用多边形创建形状无法正常工作 Java3d