# -*- coding: utf-8 -*- import os import sys import tornado.ioloop import tornado.web import tornado.wsgi import tornado.httpserver from django.core.handlers.wsgi import WSGIHandler # 设置 Django 设置模块,sets the default settings module to use _HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.append(_HERE) os.environ['DJANGO_SETTINGS_MODULE'] = "settings" def main(port):
# 利用 tornado 的http server处理消息请求 wsgi_app = tornado.wsgi.WSGIContainer(WSGIHandler())
# Application 处理请求消息 tornado_app = tornado.web.Application(
# FallbackHandler: A RequestHandler that wraps another HTTP server callback.
# http://www.tornadoweb.org/en/stable/web.html#tornado.web.FallbackHandler [('.*', tornado.web.FallbackHandler, dict(fallback=wsgi_app)), ])
# HTTPServer is a very basic connection handler. It parses the request headers and body server = tornado.httpserver.HTTPServer(tornado_app) server.listen(port) tornado.ioloop.IOLoop.instance().start() if __name__ == '__main__': try: import setproctitle setproctitle.setproctitle('www:' + sys.argv[1]) except ImportError: pass main(int(sys.argv[1]))
基本思想:利用 tornado 的 http server,处理消息请求。
官方文档有介绍:
- WSGIContainer lets you run other WSGI applications and frameworks on the Tornado HTTP server. For example, with this class you can mix Django and Tornado handlers in a single server.
详细内容,见代码注释。