tornado 学习

tornado 很合我的胃口,开始学习

tornado 像 web.py+twisted,是一个高效率非阻塞的 server,用 epoll来保证效率,但是开发起来,没有 twisted 那么别扭,而更像 web.py 那样简洁.

官方文档:http://www.tornadoweb.org/documentation

first

这是最简单的一个例子

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

很 easy,就是把 url 与 服务在建 Application 对象的时候做一个映射.

用 ioloop 做一个 loop 监听.

模块

主要模块

web

  • web - The web framework on which FriendFeed is built. web incorporates most of the important features of Tornado tornado.web.RequestHandler 实现了对 http 的一些处理,该有的都有,不细说了.

RequestHandler 的 render 方法也能实现对模版的支持,怎么用?看代码 template.py

get_cookie,set_cookie 方法方便的时现了对 cookie 的处理.

  • escape - XHTML, JSON, and URL encoding/decoding methods

    database

  • database - A simple wrapper around MySQLdb to make MySQL easier to use 带着的只有对 mysql 的封装,看来还得自己动手.

还好我以前己经写过一个对 oracle 的封装

template

  • template - A Python-based web templating language

    httpclient

  • httpclient - A non-blocking HTTP client designed to work with web and httpserver 只有这里和 iostream 能体现 tornado 的非阻塞性质

    class MainHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        http = tornado.httpclient.AsyncHTTPClient()
        http.fetch("http://friendfeed-api.com/v2/feed/bret",
                   callback=self.on_response)
    
    def on_response(self, response):
        if response.error: raise tornado.web.HTTPError(500)
        json = tornado.escape.json_decode(response.body)
        self.write("Fetched " + str(len(json![pic]("entries"))) + " entries "
                   "from the FriendFeed API")
        self.finish()

这个例子就说明了该怎么用 * auth - Implementation of third party authentication and authorization schemes (Google OpenID/OAuth, Facebook Platform, Yahoo BBAuth, FriendFeed OpenID/OAuth, Twitter OAuth) * locale - Localization/translation support * options - Command line and config file parsing, optimized for server environments

低层模块

  • httpserver - A very simple HTTP server built on which web is built

    iostream

  • iostream - A simple wrapper around non-blocking sockets to aide common reading and writing patterns 得好好看下,看是否能用这个来做 flex 的 sockets 服务. 看 iostream.py iostream 提供的功能可以说是一个 socket 客户端,作为一个 server 方,把客户端作为核心实现干什么?

我还是好好看看 python 的 SocketServer 好了 * ioloop - Core I/O loop

其它

  • s3server - A web server that implements most of the Amazon S3 interface, backed by local file storage