Last active
August 29, 2015 13:55
-
-
Save orestis/8787481 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# crochet allows non-twisted apps to call twisted code | |
import crochet | |
crochet.no_setup() | |
from twisted.application import internet, service | |
from twisted.web import server, wsgi, static, resource | |
from twisted.internet import reactor | |
from twisted.python import threadpool | |
# boilerplate to get any WSGI app running under twisted | |
class WsgiRoot(resource.Resource): | |
def __init__(self, wsgi_resource): | |
resource.Resource.__init__(self) | |
self.wsgi_resource = wsgi_resource | |
def getChild(self, path, request): | |
path0 = request.prepath.pop(0) | |
request.postpath.insert(0, path0) | |
return self.wsgi_resource | |
# create a twisted.web resource from a WSGI app. | |
def get_wsgi_resource(wsgi_app): | |
pool = threadpool.ThreadPool() | |
pool.start() | |
# Allow Ctrl-C to get you out cleanly: | |
reactor.addSystemEventTrigger('after', 'shutdown', pool.stop) | |
wsgi_resource = wsgi.WSGIResource(reactor, pool, wsgi_app) | |
return wsgi_resource | |
def start(): | |
# create an SSE resource that is effectively a singleton | |
from sse import SSEResource | |
sse_resource = SSEResource() | |
# attach its "broadcast_message" function to the WSGI app | |
from app import wsgi_app | |
wsgi_app.broadcast_message = sse_resource.broadcast_message_async | |
# serve everything together | |
root = WsgiRoot(get_wsgi_resource(wsgi_app)) # WSGI is the root | |
root.putChild("index.html", static.File("index.html")) # serve a static file | |
root.putChild("sse", sse_resource) # serve the SSE handler | |
main_site = server.Site(root) | |
server = internet.TCPServer(8005, main_site) | |
application = service.Application("twisted_wsgi_sse_integration") | |
server.setServiceParent(application) | |
return application | |
application = start() | |
# run this using twistd -ny server.py |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment