tornado 源碼包中 demos 目錄下包含一些示例程序,就從最簡單的 helloworld.py 來看一個 tornado 應用程序的代碼結構。
完整的實例程序如下:
06 |
import tornado.httpserver |
08 |
import tornado.options |
11 |
from tornado.options import define,
options |
13 |
define( "port" ,
default = 8888 , help = "run
on the given port" , type = int ) |
16 |
class MainHandler(tornado.web.RequestHandler): |
18 |
self .write( "Hello,
Nowamagic" ) |
22 |
tornado.options.parse_command_line() |
23 |
application = tornado.web.Application([ |
26 |
http_server = tornado.httpserver.HTTPServer(application) |
27 |
http_server.listen(options.port) |
28 |
tornado.ioloop.IOLoop.instance().start() |
31 |
if __name__ = = "__main__" : |
首先是一組 import。這個再正常不過了,當然,之前該有的註釋什麼的還是要有的。
1 |
import tornado.httpserver |
6 |
from tornado.options import define,
options |
接下來,是定義應用程序的選項,這樣可以在啓動應用程序的時候指定一些參數。tornado 提供了方法 tornado.options.define 來簡化了選項參數的定義,具體的可以通過 help 來查看。這裏有直接的例子,定義端口參數:
1 |
define( "port" ,
default = 8888 , help = "run
on the given port" , type = int ) |
接下來是 MainHandler 的設置:
1 |
class MainHandler(tornado.web.RequestHandler): |
3 |
self .write( "Hello,
Nowamagic" ) |
XXHandler 針對映射的 url 的具體實現。
Handler 下面是 main() 函數的定義:
2 |
tornado.options.parse_command_line() |
3 |
application = tornado.web.Application([ |
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 工作。當然,具體的實現還是比較複雜的,這裏僅僅是簡單概括一下。
總結下來,代碼組織如下: