使用Tornado作為Django App的伺服器
阿新 • • 發佈:2019-01-01
閒來無事,折騰折騰。
老是聽說tonado是個非同步web框架和伺服器,作為框架倒是瞭解到了,但是伺服器一直不太懂。所以決定了解一下,既然可以做伺服器,那就把自己的django app部署到這上邊去。
先是*Google*了一下,找到了一篇相關[部落格](https://thinkfaster.co/2015/01/run-django-on-tornado/)。於是乎,將其改造改造,直接搬過來。原作是要用*websocket*這個東東,而我只是要App部署上去就OK。發現需要的程式碼是相當精簡的。
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE" , "myblog.settings")
import django.conf
import django.contrib.auth
import django.core.handlers.wsgi
from django.core.wsgi import get_wsgi_application
import django.db
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.wsgi
from tornado.options import options, define
define('port' , type=int, default=8080)
class HelloHandler(tornado.web.RequestHandler):
def get(self):
self.write('Hello from tornado')
def main():
wsgi_app = tornado.wsgi.WSGIContainer(get_wsgi_application())
tornado_app = tornado.web.Application(
[
(r'/hello-tornado*', HelloHandler),
(r'.*' , tornado.web.FallbackHandler, dict(fallback=wsgi_app)),
])
server = tornado.httpserver.HTTPServer(tornado_app)
server.listen(options.port, address='192.168.1.59')
tornado.ioloop.IOLoop.instance().start()
if __name__ == '__main__':
main()
有一些改動,在WSGIContainer中,原作使用的是:
wsgi_app = tornado.wsgi.WSGIContainer(
django.core.handlers.wsgi.WSGIHandler())
然後自己用就報錯了The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don’t make non-lazy gettext calls at import time我勒個去。
最後發現得用
from django.core.wsgi import get_wsgi_application
用get_wsgi_application替代。
哈哈,OK,python tonado_main.py就把他給跑起來了。