server sent event

Python Cherrypy Server Sent Event SSE (eventsource)

I hardly find a good example for server sent event using cherrypy (python).  So I wrote a simple one.

@cherrypy.expose
def systime(self):
  cherrypy.response.headers["Content-Type"] = "text/event-stream;charset=utf-8"
  def timedata():
    for ii in range (10):
      yield (bytes('id: {}\ndata:{{"time":"{}"}}\n\n'
        .format(int(time.time()),
        datetime.datetime.isoformat(datetime.datetime.now())),'utf8'))
      time.sleep(1)
return timedata()
systime._cp_config = {'response.stream': True}

 

You should also add some cache control so that the browser doesn’t cache your result.

Cherrypy is not a good tool to publish SSE as it is not an async server.  You may consider using an asyncio version of cherrypy (not official) or use some async servers like Tornado or Twisted.

Advertisements