python - 如何通过 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) 线程会并行运行吗?
解决方案
hendrix
是一个让你通过 twisted 运行 django 的项目。如果需要,它看起来可以运行其他扭曲的服务(https://hendrix.readthedocs.io/en/latest/deploying-other-services/)。
如果您处于开发的早期阶段,请考虑klein
. 不过,它更类似于烧瓶而不是 django。
推荐阅读
- java - NoSuchMethodError: javassist.CtClass.getDeclaredClasses()
- java - Ticklistener 中的 Arrayupdate 应用程序崩溃
- r - 为字符串向量获取每个字符串的多个匹配项
- mysql - 具有 90% 相同列的两个不同表的最佳设计
- android - React Native iOS 构建失败,“多个命令产生”错误
- python - 使用 Python 读取位于 SharePoint 文件夹中的 Excel 工作表
- reactjs - reactjs中REF和INNERREF的区别
- javascript - 无法将 frida 函数附加到 android 本机 lib 函数
- python - 如何重新排序行,通过在 python 中使用 pandas 或 numpy 移动多个单独的行下面的 X 行
- javascript - 使用 setTimeout() 在 React 中渲染一个带有一些超时的列表