Millet Porridge

English version of https://corvo.myseu.cn

0%

Debugging all types of Python servers with Tornado

When I first meet Python web, Tornado 4.x is the first framework I used. It maybe a little hard for a beginner to use coroutine, but the pretty log just hits me.

tornado-run

When I used the WSGI protocol at work, I had to use uwsgi in production. It worked fine but it didn’t give me a convenient experience. I have to write too many settings and debug through the ugly logs.

While Tornado is using non-blocking network I/O and not based on WSGI, it could support to run WSGI server with only one thread.

Core code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import tornado.wsgi
from flask_app import application

def main():
# TornadoWSGI https://www.tornadoweb.org/en/stable/wsgi.html
container = tornado.wsgi.WSGIContainer(application)
settings = dict({
'debug': options.debug,
'autoreload': True,
})
# 主程序, 将所有请求发送到container中
tornado_app = tornado.web.Application([
('.*', tornado.web.FallbackHandler, dict(fallback=container))
], **settings)

server = tornado.httpserver.HTTPServer(tornado_app)
server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
main()

Why I use Tornado for developing

  1. Easy to portable WSGI protocol, and you won’t need uwsgi when developing
  2. Pretty and colorful log output
  3. Fast reload the server when you edit the code
  4. Use IPython..
  5. Support django, bootle, flask.

Github

You could find the example find in this repo:

https://github.com/corvofeng/BlogCode/tree/master/tornado-run

Attention

When you use WSGI protocol, you should never Tornado in the production mode, it’s only support single thread and lacks stability and scalability.