在扭曲网络下运行 Django 测试服务器
当我正在编写一个应用程序时,它使用twisted web 来服务异步请求,并使用Django 来进行正常的内容交付,我认为如果两者通过Django 的WSGI 接口在同一个twistedreactor 下运行,那就太好了。
我还想使用 Django 提供的优秀测试服务器工具来测试我的应用程序。起初,我只是创建了测试数据库并在反应器下激发了 WSGIHandler,但这不起作用,因为 WSGIHandler 看不到初始化期间创建的测试数据库。
因此,我决定编写一个解决方案,并在第一个请求上创建数据库并加载固定装置,这对于测试服务器来说很好。这是我正在使用的(精简的)脚本:
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()
我知道这有点黑客,所以如果您有更好的解决方案,请在此处报告。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能正是您正在寻找的: http://github.com/clemesha/twisted- wsgi-django
This might be exactly what you are looking for: http://github.com/clemesha/twisted-wsgi-django