使用Flask Web应用程序监视实时数据流

Dav*_*arx 5 python multithreading network-programming stream flask

这基于/sf/answers/937224081/发布的答案

我想监视数据流并将其推送到类似于上述答案的前端,但是一旦应用启动,该流就开始生成/监视数据,并且客户端始终会看到数据流的当前状态。数据流(无论它们是否正在从服务器请求数据,它都会一直运行)。

我很确定我需要通过线程将数据流与前端分开,但是我对线程/异步编程不是很熟练,并且认为我做错了。也许不是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)
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

此代码无效。“正在启动webapp ...”消息从不打印,也没有正常的烧瓶消息,并且访问所提供的URL确认该应用程序未在运行。

如何使数据监视器在后台运行,以便Flask可以访问其看到的值并将当前状态推送到客户端(甚至更好:只要客户端正在侦听,在以下情况下推送当前状态:相关值会发生变化)?

Dav*_*arx 4

我只需要改变这一行

t = threading.Thread(target=stream.monitor())
Run Code Online (Sandbox Code Playgroud)

对此:

t = threading.Thread(target=stream.monitor)
Run Code Online (Sandbox Code Playgroud)