我一直在使用Flask和Tornado發送服務器發送的事件。我接過來一看這個博客文章:服務器用Flask和Tornado發送事件
https://s-n.me/blog/2012/10/16/realtime-websites-with-flask/
,我決定嘗試寫我自己的瓶應用發送服務器發送的事件作爲一個練習。這裏是我的瓶的應用程序稱爲sse_server.py代碼:
#! /usr/bin/python
from flask import Flask, request, Response, render_template
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
app = Flask(__name__)
def event_stream():
count = 0
while True:
print 'data: {0}\n\n'.format(count)
yield 'data: {0}\n\n'.format(count)
count += 1
@app.route('/my_event_source')
def sse_request():
return Response(
event_stream(),
mimetype='text/event-stream')
@app.route('/')
def page():
return render_template('index.html')
if __name__ == '__main__':
print "Please open a web browser to http://127.0.0.1:5000."
# Spin up the app
http_server = HTTPServer(WSGIContainer(app))
http_server.listen(5000)
IOLoop.instance().start()
在我的模板文件夾,我有一個簡單的index.html頁面:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript" src="../static/sse_client.js"></script>
</head>
<body>
<h3>Test</h3>
<ul id="output">
</ul>
</body>
</html>
在我的靜態文件夾中,我有一個文件所謂sse_client.js:
var queue = [];
var interval = setInterval(function(){addItem()}, 1000);
function addItem(){
if(queue.length > 0){
var item = queue[0];
queue.shift();
$('#output').append(item);
}
}
$(document).ready(
function() {
var sse = new EventSource('/my_event_source');
console.log('blah');
sse.onmessage = function(event) {
console.log('A message has arrived!');
var list_item = '<li>' + event.data + '</li>';
console.log(list_item);
queue.push(list_item);
};
})
基本上,我的應用程序的結構是
sse/
sse_server.py
static/
sse_client.js
templates/
index.html
該應用程序顯示索引頁面,但數據沒有傳到它。我不知道我做錯了什麼。我想我需要另一套眼睛來看這個。我確定這是一件非常小而愚蠢的事情。
一旦我將龍捲風關閉,它就像一個魅力。 –