Django on Twisted Web - Using the latest twisted.web.wsgi functionality
Because of recent work by some Twisted developers, running Django on Twisted is much easier, but still a bit under documented and bleeding edge (the relevant code is in the Twisted trunk - at the time of this writing Twisted’s release version is 8.2). A couple weeks back it was announced that because of work done at Pycon 2009, Django now runs correctly off code in the Twisted trunk.
A complete Django+Twisted WSGI example
I decided that I would share my current usage of Twisted on Django by way of a simple example. I put my example code up on github, so if you want to play around with it, get it like this:
git clone git://github.com/clemesha/twisted-wsgi-django.git
Here is my Django on Twisted Web WSGI example on Github if you just want to take a look at the code with pretty syntax highlighting and all that. In the twisted-wsgi-django project you will see 3 interesting things.
mydjangoproject, which is basically an extremely simple Django project, taken right from the Django documentation, to demonstrate a working Django instance. You would replace this with you real Django project if you wanted to see if all you own Django code does in fact run cleanly under Twisted.
server.pywhich holds the Django<->Twisted WSGI code, as well as the Twisted server and application boilerplate code. To run the example you would type
./TwistedTrunk/bin/twistd -ny server.py.
twresource.pywhich holds only Twisted Web code. You can see this as the simplest possible example of where you would start writing all your Twisted code - or if you have existing Twisted code, you can see how it gets plugged in together with a running Django instance.
Once you have ran
./TwistedTrunk/bin/twistd -ny server.py, navigate to
http://localhost:8000/admin to verify that Django is running. If all bits of Django’s admin interface are working (including the css and images being there - which are being served up by an out-of-wsgi-band instance of Twisted Web’s
static.File) then you know that all is well with Django and Twisted.
Now go to the url
http://localhost:8000/google?q=somequery, which is a resource being handled completely by custom Twisted code. Behind the scenes it grabs a google query page using
twisted.web.client.getPage. As you can see if you check the source of the file
twresource.py, we are totally in Twisted land. This is where you can start plugging in some Twisted XMPP code, maybe start using Twisted’s Perspective Broker, or whatever else.
If you have an opinion on how to do this better or cleaner, please drop a note.
(my tweets are heavily tech-focused and highly non-inane.)