2014-05-15 2 views
1

Flask 프레임 워크에서 실시간 메시지를 업데이트 할 수있는 실시간 웹 응용 프로그램을 작성하려고합니다. http://flask.pocoo.org/snippets/116/의 코드를 사용하고 있지만 JavaScript EventSource SSE는 브라우저에서 실행되지 않습니다. 로그에서 데이터를 성공적으로 게시했지만 웹 페이지 (http : xxxx : 5000 /)가 전혀 업데이트되지 않음을 알 수 있습니다.Python Flask에서 SSE 프로토콜 사용

import gevent 
from gevent.wsgi import WSGIServer 
from gevent.queue import Queue 

from flask import Flask, Response 

import time 


# SSE "protocol" is described here: http://mzl.la/UPFyxY 
class ServerSentEvent(object): 

    def __init__(self, data): 
     self.data = data 
     self.event = None 
     self.id = None 
     self.desc_map = { 
      self.data : "data", 
      self.event : "event", 
      self.id : "id" 
     } 

    def encode(self): 
     if not self.data: 
      return "" 
     lines = ["%s: %s" % (v, k) 
       for k, v in self.desc_map.iteritems() if k] 

     return "%s\n\n" % "\n".join(lines) 

app = Flask(__name__) 
subscriptions = [] 

# Client code consumes like this. 
@app.route("/") 
def index(): 
    debug_template = """ 
    <!DOCTYPE html> 
    <html> 
     <head> 
     </head> 
     <body> 
     <h1>Server sent events</h1> 
     <div id="event"></div> 
     <script type="text/javascript"> 

     var eventOutputContainer = document.getElementById("event"); 
     var evtSrc = new EventSource("/subscribe"); 

     evtSrc.onmessage = function(e) { 
      console.log(e.data); 
      eventOutputContainer.innerHTML = e.data; 
     }; 

     </script> 
     </body> 
    </html> 
    """ 
    return(debug_template) 

@app.route("/debug") 
def debug(): 
    return "Currently %d subscriptions" % len(subscriptions) 

@app.route("/publish") 
def publish(): 
    #Dummy data - pick up from request for real data 
    def notify(): 
     msg = str(time.time()) 
     for sub in subscriptions[:]: 
      sub.put(msg) 

    print 'data is ' + str(time.time()) 
    gevent.spawn(notify) 

    return "OK" 

@app.route("/subscribe") 
def subscribe(): 
    def gen(): 
     q = Queue() 
     subscriptions.append(q) 
     try: 
      while True: 
       result = q.get() 
       ev = ServerSentEvent(str(result)) 
       print 'str(result) is: ' + str(result) 
       yield ev.encode() 
     except GeneratorExit: # Or maybe use flask signals 
      subscriptions.remove(q) 

    return Response(gen(), mimetype="text/event-stream") 

if __name__ == "__main__": 
    app.debug = True 
    server = WSGIServer(("", 5001), app) 
    server.serve_forever() 
    # Then visit http://localhost:5000 to subscribe 
    # and send messages by visiting http://localhost:5000/publish 

조명을 비출 수 있습니까? Chrome/34.0.1847.116으로 테스트하고 있습니다. 감사.

답변

0

기본 페이지를 열어 두었습니까?

는 그 코드를 복사하여 두 개의 탭이 열려 :

  • 메인 페이지
  • /게시 페이지

을 그리고 여러 번 다시로드 한 후/페이지를 게시, 나는 메인 페이지 업데이트를 보았다.

관련 문제