TurboGears as a Twisted WSGI Application (in 125 seconds)

Say you want to have a TurboGears application running inside a Twisted web-server (which lets you mix in all sorts of other protocols).  J.P. has written up a 60-second recipe for getting a WSGI application running inside Twisted.  This post takes you the rest of the way to getting TurboGears 2.1 running inside that Twisted environment (hopefully).

First, the script that does the actual work, most of this just looks like the 60-second script from J.P.:

from paste.script.util.logging_config import fileConfig
from paste.deploy import loadapp
from twisted.web.server import Site
from twisted.web.static import File
from twisted.web.wsgi import WSGIResource
from twisted.internet import reactor
from twisted.internet import reactor, ssl
import os

def main(config='development.ini',privkey=None,cacert=None,port=None):
if port is None:
if privkey and cacert:
port = 8443
else:
port = 8080
config = os.path.abspath( config )
fileConfig(config)
application = loadapp('config:%s'%(config,))
# Twisted WSGI server setup...
resource = WSGIResource(reactor, reactor.getThreadPool(), application)

factory = Site(resource)
if privkey and cacert:
sslContext = ssl.DefaultOpenSSLContextFactory(
privkey,
cacert,
)
reactor.listenSSL( int(port), factory, contextFactory=sslContext)
else:
reactor.listenTCP( int(port), factory )
reactor.run()

if __name__ == "__main__":
import sys
main( *sys.argv[1:] )

The only real changes there from the 60-second recipe are that we're importing the two Paste entry points (one for configuring logging, the other for configuring the application) and calling them with our config file.

To give it a whirl:

    virtualenv --no-site-packages twisted-tg
cd twisted-tg
source bin/activate
easy_install -U setuptools
easy_install -i http://www.turbogears.org/2.1/downloads/current/index tg.devtools
easy_install twisted

paster quickstart myproject
cd myproject
python setup.py develop
paster setup-app development.ini
python ../../twistedtg.py development.ini

You should now be able to browse to http://localhost:8080 and see your quick-started TurboGears 2.1 project running under Twisted 9.0.

Comments

  1. Kevin Horn

    Kevin Horn on 01/21/2010 11:46 a.m. #

    I love this post.

    LOVE.
    IT.

Comments are closed.

Pingbacks

Pingbacks are closed.