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 : 用來優(yōu)化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 , 生產(chǎn)環(huán)境建議使用Linux(epoll)和BSD(kqueue)绊困,發(fā)揮最佳性能和伸縮性船殉。window也可以用來開發(fā)薪韩,官方不建議使用生產(chǎn)宙帝。若果不重寫IOLoop interface丧凤,可能無法添加原聲的tornado windows OPLoop實(shí)現(xiàn)或者無法發(fā)揮windows的IOCP在類似asyncIO或者twisted框架中。
線程和WSGI
tornado不同于其他的很多python web 框架步脓,他不基于WSGI愿待,并且典型的是他只會在每個進(jìn)程啟動一個線程。感興趣的可以查看更多的異步編程的方法靴患。
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不是線程安全的。唯一的安全方方法是從其他的線程中調(diào)用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集成了標(biāo)準(zhǔn)庫asyncio模塊农渊,并且共享了相同的event loop(since 5.0 版本)。所以基于asncio設(shè)計(jì)的庫都可以和tornado自由融合使用或颊。
學(xué)習(xí)文檔
Documentation
This documentation is also available in PDF and Epub formats.