开发者

Running a Django test server under twisted web

开发者 https://www.devze.com 2022-12-18 02:16 出处:网络
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 react

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 impor开发者_开发技巧t 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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号