Speed up development with full-stack environments for every branch.

Learn More

Server Side Events with TurboGears2 [Python]

Forked from Request Method Dispatch in TurboGears.

68 Runs 294 Views 61 Copies
Saved

Saved

amol 16

amol
published 3 years ago

from gevent.monkey import patch_all
patch_all()

from gevent.wsgi import WSGIServer
from tg import expose, TGController, RestController, AppConfig, request
import time

# PLESE NOTE THAT CLIENT DISCONNECTION DOESN'T HAPPEN ON RUNNABLE,
# SO DOWNLOAD AND TRY THIS LOCALLY TO TEST IT.

class RootController(TGController):
    @expose('index.html')
    def index(self):
      return dict() 

    # SSE requires "text/event-stream" Content-Type
    @expose(content_type='text/event-stream')
    def data(self, **kw):
        # SSE happens on a standard controller method,
        # so entering the controller means a client connected.
        print 'CLIENT CONNECTED'
        
        # SSE Works by returning an endless generator
        # so that we will keep open forever the connection
        # continuously sending data back to the client.
        def _generator():
            try:
              while True:
                  # Send SSE data with current time each second.
                  yield "data: %s\n\n" % int(time.time())
                  time.sleep(1.0)
            except GeneratorExit: 
              # When connection gets closed TurboGears will call
              # generator .close() which raises a GeneratorExit exception.
              # so we can handle here any required cleanup
              print 'CLIENT CLOSED CONNECTION'
              raise

        return _generator()

config = AppConfig(minimal=True, root_controller=RootController())
config.renderers = ['genshi']

DEPLOY_OPTIONS = {}
httpd = WSGIServer(('', 80), config.make_wsgi_app(**DEPLOY_OPTIONS))

print "Serving on port 80..."
httpd.serve_forever()
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).