1.開始用Tornado:從Hello World開始 (副標題:瞭解Tornado代碼組織)

tornado 源碼包中 demos 目錄下包含一些示例程序,就從最簡單的 helloworld.py 來看一個 tornado 應用程序的代碼結構。

完整的實例程序如下:

01 #!/usr/bin/env python
02 #
03 # Copyright 2009 Facebook
04 #
05  
06 import tornado.httpserver
07 import tornado.ioloop
08 import tornado.options
09 import tornado.web
10  
11 from tornado.options import define, options
12  
13 define("port", default=8888help="run on the given port"type=int)
14  
15  
16 class MainHandler(tornado.web.RequestHandler):
17     def get(self):
18         self.write("Hello, Nowamagic")
19  
20  
21 def main():
22     tornado.options.parse_command_line()
23     application = tornado.web.Application([
24         (r"/", MainHandler),
25     ])
26     http_server = tornado.httpserver.HTTPServer(application)
27     http_server.listen(options.port)
28     tornado.ioloop.IOLoop.instance().start()
29  
30  
31 if __name__ == "__main__":
32     main()

首先是一組 import。這個再正常不過了,當然,之前該有的註釋什麼的還是要有的。

1 import tornado.httpserver
2 import tornado.ioloop
3 import tornado.options
4 import tornado.web
5  
6 from tornado.options import define, options

接下來,是定義應用程序的選項,這樣可以在啓動應用程序的時候指定一些參數。tornado 提供了方法 tornado.options.define 來簡化了選項參數的定義,具體的可以通過 help 來查看。這裏有直接的例子,定義端口參數:

1 define("port", default=8888help="run on the given port"type=int)

接下來是 MainHandler 的設置:

1 class MainHandler(tornado.web.RequestHandler):
2     def get(self):
3         self.write("Hello, Nowamagic")

XXHandler 針對映射的 url 的具體實現。

Handler 下面是 main() 函數的定義:

1 def main():
2     tornado.options.parse_command_line()
3     application = tornado.web.Application([
4         (r"/", MainHandler),
5     ])
6     http_server = tornado.httpserver.HTTPServer(application)
7     http_server.listen(options.port)
8     tornado.ioloop.IOLoop.instance().start()

應用程序執行時,會先解析選擇參數。之後創建一個 Application 實例並傳遞給 HTTPServer 實例,之後啓動這個實例,到此,http server 啓動了。tornado.httpserver 模塊用來支持非阻塞的 HTTP Server。

啓動服務器之後,還需要啓動 IOLoop 的實例,這樣可以啓動事件循環機制,配合非阻塞的 HTTP Server 工作。當然,具體的實現還是比較複雜的,這裏僅僅是簡單概括一下。

總結下來,代碼組織如下:

1 註釋 
2 import 語句 
3 選項參數定義 
4 Application定義 
5 BaseHandler定義 
6 XXHandlers定義 
7 main()定義 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章