首页 > 解决方案 > 如何通过 Twisted 的 Web 服务器正确地为 Django 应用程序提供服务?

问题描述

我正在构建一个系统,它是一些将在自己的进程或线程中运行的组件。他们需要相互交流。其中一个组件是 Django 应用程序,与 Django 应用程序的内部通信不会通过 HTTP 完成。在寻找网络库时我发现了 Twisted(很棒的库!),阅读它的文档后我发现 Twisted也实现了 WSGI 规范,所以我认为它的Web 服务器可以为 Django 之类的 WSGI 应用程序提供服务。按照文档,我提供了以下脚本来为 Django 应用程序提供服务:

from twisted.web import server
from twisted.internet import reactor, endpoints
from twisted.web.wsgi import WSGIResource
from twisted.python.threadpool import ThreadPool
from mysite.wsgi import application as django_application

# Create and start a thread pool to handle incoming HTTP requests
djangoweb_threadpool = ThreadPool()
djangoweb_threadpool.start()
# Cleanup the threads when Twisted stops
reactor.addSystemEventTrigger('after', 'shutdown', djangoweb_threadpool.stop)

# Setup a twisted Service that will run the Django web app
djangoweb_request_handler = server.Site(WSGIResource(reactor, djangoweb_threadpool, django_application))
djangoweb_server = endpoints.TCP4ServerEndpoint(reactor, 8000)
djangoweb_server.listen(djangoweb_request_handler)

reactor.run()

将它保存在一个文件中,就像runserver.py在同一个目录下manage.py,你可以通过运行来启动WSGI服务器python runserver.py
我做了一个 django 视图,它执行阻塞调用time.sleep()来测试它,它工作得很好。由于它是多线程的,它没有阻塞其他请求。所以我认为它适用于同步 Django 代码。我可以使用自定义协议设置另一个服务作为内部通信的网关。
1) 该脚本是否正确加载了 Django 应用程序?它会像 gunicorn 和 uwsgi 等其他 WSGI 服务器一样工作吗?
2) 线程会并行运行吗?

标签: pythondjangomultithreadingtwistedwsgi

解决方案


hendrix是一个让你通过 twisted 运行 django 的项目。如果需要,它看起来可以运行其他扭曲的服务(https://hendrix.readthedocs.io/en/latest/deploying-other-services/)。

如果您处于开发的早期阶段,请考虑klein. 不过,它更类似于烧瓶而不是 django。


推荐阅读