2014-04-22 22 views
2

我一直在使用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 

該應用程序顯示索引頁面,但數據沒有傳到它。我不知道我做錯了什麼。我想我需要另一套眼睛來看這個。我確定這是一件非常小而愚蠢的事情。

回答

3

龍捲風的WSGIContainer不支持從WSGI應用流的響應。您可以將Flask與多線程或基於greenlet的wsgi服務器一起使用,也可以使用Tornado的本地RequestHandler接口,但在將Flask和Tornado與WSGIContainer結合使用時不能使用。

結合燒瓶和龍捲風通常不是一個好主意;見https://github.com/mitsuhiko/flask/issues/986

+0

一旦我將龍捲風關閉,它就像一個魅力。 –

0

要使用url "../static/sse_client.js"您需要Web服務器或您的Flask應用程序來提供靜態JavaScript文件。從燒瓶文檔:

要生成靜態文件的URL,使用特殊的「靜態」端點 名稱:

url_for('static', filename='style.css')

文件必須存儲在文件系統中的靜態/風格的CSS。

Read more

+0

這不是問題在這裏,我想。 – Ale