一个应用例子:
#!/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种。
- 使用get_wsgi_application()
from django.core.wsgi import get_wsgi_application
wsgi_app = tornado.wsgi.WSGIContainer(get_wsgi_application()) - 使用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()
未解决问题
- 虽然get_wsgi_application() 被推荐使用,但是还是不明白为什么 WSGIHandler() 用不了。