【发布时间】:2025-12-19 08:40:06
【问题描述】:
这是基于https://*.com/a/13388915/819544发布的答案
我想监控数据流并将其推送到与上述答案类似的前端,但是一旦应用程序启动,流就会开始生成/监控数据,并且客户端总是看到当前数据流的状态(无论它们是否从服务器请求数据,它都会继续运行)。
我很确定我需要通过线程将数据流与前端分离,但我对线程/异步编程不太熟悉,我认为我做错了。也许我需要使用多处理而不是threading?这大致是我想要做的(根据上面链接的答案修改):
app.py
#!/usr/bin/env python
from __future__ import division
import itertools
import time
from flask import Flask, Response, redirect, request, url_for
from random import gauss
import threading
app = Flask(__name__)
# Generate streaming data and calculate statistics from it
class MyStreamMonitor(object):
def __init__(self):
self.sum = 0
self.count = 0
@property
def mu(self):
try:
outv = self.sum/self.count
except:
outv = 0
return outv
def generate_values(self):
while True:
time.sleep(.1) # an artificial delay
yield gauss(0,1)
def monitor(self, report_interval=1):
print "Starting data stream..."
for x in self.generate_values():
self.sum += x
self.count += 1
stream = MyStreamMonitor()
@app.route('/')
def index():
if request.headers.get('accept') == 'text/event-stream':
def events():
while True:
yield "data: %s %d\n\n" % (stream.count, stream.mu)
time.sleep(.01) # artificial delay. would rather push whenever values are updated.
return Response(events(), content_type='text/event-stream')
return redirect(url_for('static', filename='index.html'))
if __name__ == "__main__":
# Data monitor should start as soon as the app is started.
t = threading.Thread(target=stream.monitor() )
t.start()
print "Starting webapp..." # we never get to this point.
app.run(host='localhost', port=23423)
static/index.html
<!doctype html>
<title>Server Send Events Demo</title>
<style>
#data {
text-align: center;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
if (!!window.EventSource) {
var source = new EventSource('/');
source.onmessage = function(e) {
$("#data").text(e.data);
}
}
</script>
<div id="data">nothing received yet</div>
此代码不起作用。 “正在启动 webapp...”消息永远不会打印,正常的烧瓶消息也不会打印,并且访问提供的 URL 确认应用程序没有运行。
如何让数据监视器在后台运行,使烧瓶可以访问它看到的值并将当前状态推送到客户端(更好的是:只要客户端正在监听,推送相关值发生变化时的当前状态)?
【问题讨论】:
-
你了解Python中
some_function和some_function()的区别吗? -
是的,我愿意。我明白你在暗示什么:我会尝试将函数对象发送到线程而不是调用它。我的错。我现在实际上正在尝试一些完全不同的东西:在完全独立的控制台中运行数据馈送,并使用 redis.pubsub 将当前状态传达给 webapp。我对这个解决方案持乐观态度,但遇到了一些奇怪的事情。仍然会继续使用线程,感谢您指出该错误。
-
哈哈,知道了。看起来像修复了它!谢谢。
标签: python multithreading flask stream network-programming