Last active
February 20, 2016 17:43
-
-
Save appendjeff/ee67913d19f78e936eec to your computer and use it in GitHub Desktop.
Twisted implementation to run Django asynchronously on the network layer
This file contains hidden or 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
| import sys, os | |
| from twisted.application import internet, service | |
| from twisted.web import server, resource, wsgi, static | |
| from twisted.python import threadpool | |
| from twisted.internet import reactor, protocol | |
| from twisted.internet import defer | |
| from twisted.web.resource import Resource | |
| class TwistedDjangoException(Exception): | |
| pass | |
| PORT = 4000 | |
| PROJECT_NAME = "" | |
| if not PROJECT_NAME: | |
| raise TwistedDjangoException('Please update the PROJECT_NAME. ' +\ | |
| 'This should be the name of the folder that has your django code.') | |
| class TwistedDjangoRoot(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 | |
| class ThreadPoolService(service.Service): | |
| def __init__(self, pool): | |
| self.pool = pool | |
| def startService(self): | |
| service.Service.startService(self) | |
| self.pool.start() | |
| def stopService(self): | |
| service.Service.stopService(self) | |
| self.pool.stop() | |
| # Environment for Django | |
| #sys.path.append(PROJECT_NAME) | |
| os.environ['DJANGO_SETTINGS_MODULE'] = '%s.settings' % PROJECT_NAME | |
| # Twisted Application | |
| application = service.Application('twisted-django') | |
| # Twisted thread pool for Application | |
| multi = service.MultiService() | |
| pool = threadpool.ThreadPool() | |
| tps = ThreadPoolService(pool) | |
| tps.setServiceParent(multi) | |
| #Connect Django to Twisted | |
| from django.core.wsgi import get_wsgi_application | |
| resource = wsgi.WSGIResource(reactor, tps.pool, get_wsgi_application()) | |
| root = TwistedDjangoRoot(resource) | |
| #Static Files (serving these through something like nginx is recommended for production) | |
| #Path assumed: .../project_environment/PROJECT_NAME/static/ | |
| # static_files_directory = os.path.join(os.path.abspath("."), PROJECT_NAME, "static") | |
| # staticsrc = static.File(static_path) | |
| # root.putChild("static", staticsrc) | |
| # Twisted Server | |
| main_site = server.Site(root) | |
| internet.TCPServer(PORT, main_site).setServiceParent(multi) | |
| multi.setServiceParent(application) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment