tornado 学习手册1

Tornado(5.1+ )

Hello world

搭建一个简答的web app

hello_world.py


#!/usr/bin/python

# coding=utf-8

"""

tornado demo 1 简单的hello world web app

"""

import sys

import logging

import tornado.ioloop

import tornado.web

class MainHandler(tornado.web.RequestHandler):

def get(self):

self.write("hello world")

url = [(r'/', MainHandler),

]

def app():

global url

return tornado.web.Application(url)

if __name__ == "__main__":

logging.getLogger().handlers = []

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG,

format='%(asctime)s %(levelname)s %(message)s')

ap = app()

ap.listen(9991)

logging.info("starting ....")

tornado.ioloop.IOLoop.current().start()

logging.info("end.")

使用python 启动后,在浏览器访问

python hello_world.py

安装

使用pip源安装

pip install tornado

依赖:

tornado6.0依赖python3.5.2或者更新版本不支持python2(5.1可以支持2.7和3.4+)。

Pycurl : 用来优化tornado.curl_httpclient,libcurl version 7.22或者更高版本

Twisted: may be used with the classes in [**tornado.platform.twisted**](https://www.tornadoweb.org/en/branch5.1/twisted.html#module-tornado.platform.twisted).

pycares: is an alternative non-blocking DNS resolver that can be used when threads are not appropriate.

  • monotonic or Monotime : add support for a monotonic clock, which improves reliability in environments where clock adjustments are frequent. No longer needed in Python 3.

平台: unix-like , 生产环境建议使用Linux(epoll)和BSD(kqueue),发挥最佳性能和伸缩性。window也可以用来开发,官方不建议使用生产。若果不重写IOLoop interface,可能无法添加原声的tornado windows OPLoop实现或者无法发挥windows的IOCP在类似asyncIO或者twisted框架中。

线程和WSGI

tornado不同于其他的很多python web 框架,他不基于WSGI,并且典型的是他只会在每个进程启动一个线程。感兴趣的可以查看更多的异步编程的方法。

While some support of WSGI is available in the [tornado.wsgi](https://www.tornadoweb.org/en/branch5.1/wsgi.html#module-tornado.wsgi) module, it is not a focus of development and most applications should be written to use Tornado’s own interfaces (such as [tornado.web](https://www.tornadoweb.org/en/branch5.1/web.html#module-tornado.web)) directly instead of using WSGI.

通常,tornado的code不是线程安全的。唯一的安全方方法是从其他的线程中调用IOLop.add_callback。(In general, Tornado code is not thread-safe. The only method in Tornado that is safe to call from other threads is [IOLoop.add_callback](https://www.tornadoweb.org/en/branch5.1/ioloop.html#tornado.ioloop.IOLoop.add_callback). You can also use [IOLoop.run_in_executor](https://www.tornadoweb.org/en/branch5.1/ioloop.html#tornado.ioloop.IOLoop.run_in_executor) to asynchronously run a blocking function on another thread, but note that the function passed to run_in_executor should avoid referencing any Tornado objects. run_in_executor is the recommended way to interact with blocking code.)

异步io集成

tornado集成了标准库asyncio模块,并且共享了相同的event loop(since 5.0 版本)。所以基于asncio设计的库都可以和tornado自由融合使用。

学习文档

Documentation

This documentation is also available in PDF and Epub formats.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容