使用Tornado作为Django App的WSGI容器

一个应用例子:


#!/usr/bin/env python
#*_* coding=utf8 *_*

import os
import sys
import logging

from tornado.options import options, define, parse_command_line
import django.core.handlers.wsgi
# use get_wsgi_application
from django.core.wsgi import get_wsgi_application

import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.wsgi

sys.path.append(os.path.dirname(os.path.abspath(__file__)))
os.environ['DJANGO_SETTINGS_MODULE'] = "cmdb.settings"

define('port', type=int, default=8000)
#www.iplaypy.com

def main():
    parse_command_line()

    #wsgi_app = tornado.wsgi.WSGIContainer(
    #    django.core.handlers.wsgi.WSGIHandler())

    wsgi_app = tornado.wsgi.WSGIContainer(get_wsgi_application())

    tornado_app = tornado.web.Application(
        [('.*', tornado.web.FallbackHandler, dict(fallback=wsgi_app)),
        ])
    server = tornado.httpserver.HTTPServer(tornado_app)
    server.listen(options.port)
    logging.warn("[CMDB] CMDB is running on: localhost:%d", options.port)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == '__main__':
    main()

扩展阅读:

如何使用tornado运行Django

http://www.iplaypy.com/code/other/o2428.html
简介:

玩蛇网的一个简单示例。


#*_* coding=utf8 *_*
#!/usr/bin/env python
import os
import sys
  
from tornado.options import options, define, parse_command_line
import django.core.handlers.wsgi
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.wsgi
  
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
os.environ['DJANGO_SETTINGS_MODULE'] = "settings"
  
define('port', type=int, default=8088)
#www.iplaypy.com
  
def main():
    parse_command_line()
  
    wsgi_app = tornado.wsgi.WSGIContainer(
        django.core.handlers.wsgi.WSGIHandler())
  
    tornado_app = tornado.web.Application(
        [('.*', tornado.web.FallbackHandler, dict(fallback=wsgi_app)),
        ])
    server = tornado.httpserver.HTTPServer(tornado_app)
    server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()
  
if __name__ == '__main__':
    main()

使用Tornado作为Django App的服务器

http://blog.csdn.net/fancyyuan/article/details/49383575
简介:

CSDN 上的一篇博客。

这篇比较靠谱,使用

from django.core.wsgi import get_wsgi_application
wsgi_app = tornado.wsgi.WSGIContainer(get_wsgi_application())
代替

wsgi_app = tornado.wsgi.WSGIContainer(
django.core.handlers.wsgi.WSGIHandler())

在生产系统使用Tornado WebServer来代替FastCGI加速你的Django应用

http://www.cnblogs.com/Alexander-Lee/archive/2011/05/02/tornado_host_django.html
简介:
介绍比较全面,但还是使用了

wsgi_app = tornado.wsgi.WSGIContainer(
django.core.handlers.wsgi.WSGIHandler())

django 源码分析:

django 工程中的wsgi.py

filename: wsgi.py

WSGI config for cmdb project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cmdb.settings")

application = get_wsgi_application()

django 源码中的wsgi.py

filename: django/core/wsgi.py

import django
from django.core.handlers.wsgi import WSGIHandler


def get_wsgi_application():
    """
    The public interface to Django's WSGI support. Should return a WSGI
    callable.

    Allows us to avoid making django.core.handlers.WSGIHandler public API, in
    case the internal WSGI implementation changes or moves in the future.
    """
    django.setup(set_prefix=False)
    return WSGIHandler()

常见问题及解决

问题:


[E 170723 03:39:28 web:1590] Uncaught exception GET /cmdb/api/property_list/item_testaa/ (172.28.32.51)
    HTTPServerRequest(protocol='http', host='cmdb-test.syswin.com', method='GET', uri='/cmdb/api/property_list/item_testaa/', version='HTTP/1
.0', remote_ip='172.28.32.51', headers={'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6', 'Accept-Encoding': 'gzip, deflate', 'Host': 'cmdb-test.
syswin.com', 'Accept': 'application/json, text/plain, */*', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36
 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36', 'Connection': 'close', 'X-Requested-With': 'XMLHttpRequest', 'Pragma': 'no-cache',
'Cache-Control': 'no-cache', 'Referer': 'http://cmdb-test.syswin.com/', 'Cookie': 'PROD=cZsaLhqoGI7WTnpqhIb5c7fK3u; ExpirePage=http://ehrkj.s
yswin.com/psp/ps/; PS_LOGINLIST=http://ehrkj.syswin.com/ps; PS_TOKEN=AAAApQECAwQAAQAAAAACvAAAAAAAAAAsAARTaGRyAgBObQgAOAAuADEAMBQgZjqFU3EEy1ac
XaEUspfkaaetzgAAAGUABVNkYXRhWXicHYxRDkAwEERfEV/iJpq2qPQC4lPUlx8ncEOHM7WbvJ3JTBZ4TFU3GDTVW9gRcdqAJ7RcbOSenczKyS17TAqd4oVBt9CTfj1imeWsGkmMYnnkp
T5Angr6; SignOnDefault=600212; http%3a%2f%2fehrkj.syswin.com%2fpsp%2fps%2femployee%2fhrms%2frefresh=list:%20%3Ftab%3Dhc_ux_manager_dashboard%
7C%3Frp%3Dhc_ux_manager_dashboard%7C%3Ftab%3Dremoteunifieddashboard%7C%3Frp%3Dremoteunifieddashboard; PS_TOKENEXPIRE=19_Jul_2017_02:46:17_GMT
'})
    Traceback (most recent call last):
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/tornado/web.py", line 1488, in _execute
        result = self.prepare()
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/tornado/web.py", line 2774, in prepare
        self.fallback(self.request)
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/tornado/wsgi.py", line 277, in __call__
        WSGIContainer.environ(request), start_response)
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 189, in __call__
        response = self.get_response(request)
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/core/handlers/base.py", line 218, in get_response
        response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/core/handlers/base.py", line 268, in handle_uncaught_exception
        return callback(request, **param_dict)

      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view
        response = view_func(request, *args, **kwargs)
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/views/defaults.py", line 42, in server_error
        template = loader.get_template(template_name)
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/template/loader.py", line 35, in get_template
        return engine.get_template(template_name, dirs)
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/template/backends/django.py", line 30, in get_template
        return Template(self.engine.get_template(template_name, dirs))
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/template/engine.py", line 167, in get_template
        template, origin = self.find_template(template_name, dirs)
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/template/engine.py", line 141, in find_template
        source, display_name = loader(name, dirs)
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/template/loaders/base.py", line 13, in __call__
        return self.load_template(template_name, template_dirs)
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/template/loaders/base.py", line 17, in load_template
        template_name, template_dirs)
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/template/loaders/app_directories.py", line 36, in load_template_source
        for filepath in self.get_template_sources(template_name, template_dirs):
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/template/loaders/app_directories.py", line 26, in get_template_sources
        template_dirs = get_app_template_dirs('templates')
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/utils/lru_cache.py", line 125, in wrapper
        result = user_function(*args, **kwds)
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/template/utils.py", line 122, in get_app_template_dirs
        for app_config in apps.get_app_configs():
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/apps/registry.py", line 137, in get_app_configs
        self.check_apps_ready()
      File "/root/.virtualenvs/py2.7.13mpc_cmdb/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready
        raise AppRegistryNotReady("Apps aren't loaded yet.")
    AppRegistryNotReady: Apps aren't loaded yet.
[E 170723 03:39:28 web:2063] 500 GET /cmdb/api/property_list/item_testaa/ (172.28.32.51) 4.30ms

解决:
使用tornado启动django的写法主要有2种。

  1. 使用get_wsgi_application()
    from django.core.wsgi import get_wsgi_application
    wsgi_app = tornado.wsgi.WSGIContainer(get_wsgi_application())
  2. 使用django.core.handlers.wsgi.WSGIHandler()
    wsgi_app = tornado.wsgi.WSGIContainer(
    django.core.handlers.wsgi.WSGIHandler())
    使用方法2可能有问题,出现类似AppRegistryNotReady: Apps aren't loaded yet.的问题。推荐的写法为get_wsgi_application()

未解决问题

  1. 虽然get_wsgi_application() 被推荐使用,但是还是不明白为什么 WSGIHandler() 用不了。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,670评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,928评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,926评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,238评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,112评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,138评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,545评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,232评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,496评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,596评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,369评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,226评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,600评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,906评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,185评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,516评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,721评论 2 335

推荐阅读更多精彩内容