views:

322

answers:

1

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.

+1  A: 

This might be exactly what you are looking for: http://github.com/clemesha/twisted-wsgi-django

clemesha
Thanks for the link. I've not tried it, but I think it doesn't solve the problem of running the django site in test mode. Or it does so?
Cristiano Paris