As I'm writing an application which uses twisted web for serving async requests and Django for normal content delivery, I thought it would have been nice to have both run under the same twisted reactor through the WSGI interface of Django.
I also wanted to test my app using the nice test server facility that Django offers. At first I simply created the test db and fired the WSGIHandler under the reactor but this didn't work as the WSGIHandler doesn't see the test db created during the initialization.
Hence, I decided to write a work around and have the db created and fixtures loaded on the first request, which is fine for a test server. Here's the (stripped down) script I'm using:
import os, sys
import django.core.handlers.wsgi
from django.core.management import call_command
from django.db import connection
from twisted.web.wsgi import WSGIResource
from twisted.internet import reactor
from twisted.web.server import Site
sys.path.append('/path/to/myapp')
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
_app = django.core.handlers.wsgi.WSGIHandler()
initialized = False
fixtures = (...) # Put your fixtures path here
def app(e,sr):
global initialized
if not initialized:
connection.creation.create_test_db(verbosity=1)
call_command('loaddata', *fixtures, verbosity=1)
initialized = True
return _app(e,sr)
res = WSGIResource(reactor, reactor.getThreadPool(), app)
factory = Site(res)
reactor.listenTCP(8888, factory)
reactor.run()
I know this is a bit of a hack so if you've a better solution please report it here.
Thanks.