tornado 文档说明
WSGI对Tornado Web框架的支持。
WSGI是Web服务器的Python标准,并允许Tornado与其他Python Web框架和服务器之间的互操作性。
该模块通过 WSGIContainer 类提供 WSGI 支持,这使得在 Tornado HTTP 服务器上使用其他 WSGI 框架运行应用程序成为可能。不支持相反的操作; Tornado Application 和 RequestHandler 类设计用于 Tornado HTTPServer ,不能在通用 WSGI
容器中使用。
classtornado.wsgi.WSGIContainer(wsgi_application: WSGIAppType)
使与WSGI兼容的功能可在Tornado的HTTP服务器上运行。
警告 WSGI is a synchronous interface, while Tornado’s concurrency model is based on single-threaded asynchronous execution. This means that running a WSGI app with Tornado’s WSGIContainer is less scalable than running the same app in a multi-threaded WSGI server like gunicorn or uwsgi. Use WSGIContainer only when there are benefits to combining Tornado and WSGI in the same process that outweigh the reduced scalability.
使用过程中需要时刻注意合并后性能问题
将WSGI函数包装在中 WSGIContainer 并将其传递 HTTPServer 以运行它。例如:
def simple_app(environ, start_response):
status = "200 OK"
response_headers = [("Content-type", "text/plain")]
start_response(status, response_headers)
return ["Hello world!\n"]
container = tornado.wsgi.WSGIContainer(simple_app)
http_server = tornado.httpserver.HTTPServer(container)
http_server.listen(8888)
tornado.ioloop.IOLoop.current().start()
此类旨在让其他框架(Django,web.py等)在 Tornado HTTP 服务器和 I/O 循环上运行。
主要目录结构
Vbox
├── apps
├── manage.py
├── Vbox
│ ├── asgi.py
│ ├── __init__.py
│ ├── __pycache__
│ ├── routing.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── service.py
实际操作
# service.py
from tornado.options import options, define, parse_command_line
import django.core.handlers.wsgi
from django.core.wsgi import get_wsgi_application
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.wsgi
import os, sys
define('port', type=int, help="run on the given port", default=60015)
class HelloHandler(tornado.web.RequestHandler):
def get(self):
self.write('Hello from tornado')
def main():
parse_command_line()
os.environ['DJANGO_SETTINGS_MODULE'] = 'Vbox.settings' # 必须指定
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/Vbox')
django_wsgi_app = get_wsgi_application()
wsgi_django_container = tornado.wsgi.WSGIContainer(django_wsgi_app)
tornado_app = tornado.web.Application(
[
('/hello-tornado', HelloHandler),
('.*', tornado.web.FallbackHandler, dict(fallback=wsgi_django_container)),
])
server = tornado.httpserver.HTTPServer(tornado_app)
server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == '__main__':
main()
- 启动django后需要单独启动tornado服务
- 本例tornado与django不同源
生命周期
如下图是django生命周期
tornado使用django wsgi,django 中间件对tornado服务不适用,但是对于 /favicon.ico
的请求仍然经过django中间件
利用django处理请求和一般业务,使用tornado以及协程处理websocket可以提升某些服务的可用性
待解决问题
- 混合使用时,websokcet 如何使用django orm存储日志
- 如何配置同源tornado服务