我正在尝试使用Flask micro-web框架上的服务器推送功能构建一个小型站点,但我不知道是否有一个框架可以直接使用.
我使用了Juggernaut,但它似乎没有在当前版本中使用redis-py,并且Juggernaut最近被弃用了.
有没有人对我的案子有任何建议?
我有多个客户端尝试连接到服务器发送的事件流/stream.这适用于单个客户端,但尝试连接任何其他客户端会导致新客户端无限期地阻塞等待数据.如果我发送更多数据,它只会发送给第一个客户端,而不会发送给其他客户端.
这是一个小片段,说明了我的问题:
import flask
import time
app = flask.Flask(__name__)
def event_stream():
for i in xrange(9999):
yield "data: %d\n\n" % i
time.sleep(1)
@app.route("/stream", methods=[ "GET" ])
def stream():
return flask.Response(
event_stream(),
mimetype="text/event-stream"
)
Run Code Online (Sandbox Code Playgroud)
然后我运行它gunicorn --worker-class=gevent -w 4 -t 99999 app:app.它适用于单个客户端,但任何其他客户端在发布时都会被阻止GET /stream.
阻止的原因是什么,我该如何解决?
我调试了一点,得到了一些奇怪的结果.如果我执行此过程,则会发生以下情况:
从问题:
代码运行正常,我想修改函数g(),但请求参数不能传入g(),它引发了一个RuntimeError: working outside of request context.
我已经调试了很长时间,我不知道如何修改它,你能帮助查看代码并解释错误背后的原因吗?
谢谢.
我的代码是:
@app.route('/username', methods=['GET', 'POST'])
def index():
req =request
print req
print "111------------" + req.method + "\n"
def ggg1(req):
print req # the req not my pass into the req....
print "444------------" + req.method + "\n"
if req.method == 'POST':
if request.form['username']:
urlList = request.form['username'].splitlines()
i = 0
for url in urlList():
i += 1
resultStr = chkListPageContent(url, getUrlContent(url), "script")
print i, resultStr
yield i, resultStr …Run Code Online (Sandbox Code Playgroud) 这基于/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, …Run Code Online (Sandbox Code Playgroud)