python实时数据流_python – 使用烧瓶web-app监控实时数据流
這是基于
https://stackoverflow.com/a/13388915/819544發(fā)布的答案
我想監(jiān)視一個(gè)數(shù)據(jù)流并將其推送到類似于上面答案的前端,但是一旦應(yīng)用程序啟動(dòng),流就開始生成/監(jiān)視數(shù)據(jù),并且客戶端總是看到當(dāng)前的狀態(tài)數(shù)據(jù)流(無論是否從服務(wù)器請求數(shù)據(jù),它都會(huì)繼續(xù)運(yùn)行).
我很確定我需要通過線程將數(shù)據(jù)流與前端分開,但我對線程/異步編程并不是很熟練,并且相信我做錯(cuò)了.也許不是線程我需要使用多處理?這是我正在嘗試做的大致(從上面鏈接的答案修改):
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)
靜態(tài)/ index.html的
Server Send Events Demo#data {
text-align: center;
}
if (!!window.EventSource) {
var source = new EventSource('/');
source.onmessage = function(e) {
$("#data").text(e.data);
}
}
nothing received yet此代碼不起作用. “正在啟動(dòng)webapp …”消息永遠(yuǎn)不會(huì)打印,也不會(huì)顯示正常的消息,并且訪問提供的URL會(huì)確認(rèn)應(yīng)用程序未運(yùn)行.
如何使數(shù)據(jù)監(jiān)視器在后臺(tái)運(yùn)行,以便燒瓶可以訪問它所看到的值并將當(dāng)前狀態(tài)推送到客戶端(更好的是:只要客戶端正在監(jiān)聽,就推送當(dāng)前狀態(tài)相關(guān)價(jià)值變化)?
總結(jié)
以上是生活随笔為你收集整理的python实时数据流_python – 使用烧瓶web-app监控实时数据流的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 新手一小时就写出人工智能应用 - 看图识
- 下一篇: python迷宫算法及实现_Python