Skip to content

Instantly share code, notes, and snippets.

@allanlei
Created July 16, 2014 03:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save allanlei/8ea15ceeae93447f7212 to your computer and use it in GitHub Desktop.
Save allanlei/8ea15ceeae93447f7212 to your computer and use it in GitHub Desktop.
Running twisted application without twistd
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.web.static import File
from twisted.web import server
from twisted.application import internet, service
from twisted.application.app import startApplication
from twisted.web.wsgi import WSGIResource
from twisted.runner.procmon import ProcessMonitor
from twisted.web import vhost, static
# Static
def getService_static(port=8880):
"""
Static file serving
"""
mounts = Resource()
mounts.putChild("foo", File("/tmp"))
# mounts.putChild("bar", File("/lost+found"))
mounts.putChild("baz", File("/opt"))
return internet.TCPServer(port, server.Site(mounts))
# WSGI
def getService_wsgi(port=8000):
"""
WSGI Service
"""
from flask import Flask
app = Flask('test')
@app.route('/')
def index():
return 'Hello world'
site = server.Site(WSGIResource(reactor, reactor.getThreadPool(), app))
return internet.TCPServer(8000, site)
# vhosts
def getService_wsgi_vhost(port=8000):
"""
WSGI Service
"""
from flask import Flask, request
app = Flask('test')
@app.route('/')
def index():
return request.host_url
def wsgi_application(environ, start_response):
start_response('200 OK', [('Content-type', 'text/plain')])
return ['Hello, world!']
router = vhost.NameVirtualHost()
router.default = static.File('/tmp')
# Add vhost
router.addHost('example.com', WSGIResource(reactor, reactor.getThreadPool(), wsgi_application))
return internet.TCPServer(8100, server.Site(router))
# Process Monitor
def getService_procmon():
"""
External Processes Services
"""
service = ProcessMonitor()
service.addProcess('static', ['python', '-m', 'SimpleHTTPServer', '9090'])
return service
if __name__ == '__main__':
application = service.Application('web')
getService_static().setServiceParent(application)
getService_wsgi().setServiceParent(application)
getService_wsgi_vhost().setServiceParent(application)
getService_procmon().setServiceParent(application)
startApplication(application, 0)
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment