<h2>Redis是过度的:使用服务器端事件</h2>
<p>派对迟到了(和往常一样),但IMHO使用Redis可能有点过头了。</p>
<p>只要在Python+Flask中工作,就可以考虑使用<a href="https://medium.com/code-zen/python-generator-and-html-server-sent-events-3cdf14140e56" rel="noreferrer">this excellent article by Panisuan Joe Chasinga</a>中描述的生成器函数。其要点是:</p>
<h2>在客户端index.html中</h2>
<pre><code>var targetContainer = document.getElementById("target_div");
var eventSource = new EventSource("/stream")
eventSource.onmessage = function(e) {
targetContainer.innerHTML = e.data;
};
...
<div id="target_div">Watch this space...</div>
</code></pre>
<h2>在烧瓶服务器中:</h2>
<pre><code>def get_message():
'''this could be any function that blocks until data is ready'''
time.sleep(1.0)
s = time.ctime(time.time())
return s
@app.route('/')
def root():
return render_template('index.html')
@app.route('/stream')
def stream():
def eventStream():
while True:
# wait for source data to be available, then push it
yield 'data: {}\n\n'.format(get_message())
return Response(eventStream(), mimetype="text/event-stream")
</code></pre>