这是基于发布在https://stackoverflow.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 %dnn" % (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…"消息永远不会打印,正常的flask消息也不会打印,访问提供的URL会确认该应用程序没有运行。
我如何让数据监视器在后台运行,使flask可以访问它看到的值,并将当前状态推送给客户端(甚至更好:只要客户端在监听,当相关值发生变化时,推送当前状态)?
我只需要更改这行
t = threading.Thread(target=stream.monitor())
到此:
t = threading.Thread(target=stream.monitor)