tornado架构分析1 从helloworld分析tornado架构

    最近公司须要我写一个高性能RESTful服务组件。我以前不多涉及这种高性能服务器架构,帮公司和平时没事玩都是写脚本级别的东西。虽然好多基础组件(sphinx、logging、configparse等)都知道一点,可是就是不知道怎么能写一个完备的服务器。看到网友们都说分析现成的python项目代码很是涨经验。我决定分析一下tornado看看,在这里把分析的体悟写在这里。python

    软件版本:tornado 4.5.2 stableweb

    分析原点:官方包自带helloworld.py,位于/demos/helloworld/helloworld.pyexpress

    分析目的:从helloworld去查看tornado在后台作了什么,尝试着还原一个高性能服务器程序编写实现的过程,尤为针对日志,参数解析,主程序循环等部分。并不针对web部分apache

    个人基础:具有python编程基础,了解http原理及包结构,了解一些经常使用包及用法。能看懂一些python语法编程

来吧,开始:服务器

 1 #!/usr/bin/env python
 2 #
 3 # Copyright 2009 Facebook
 4 #
 5 # Licensed under the Apache License, Version 2.0 (the "License"); you may
 6 # not use this file except in compliance with the License. You may obtain
 7 # a copy of the License at
 8 #
 9 #     http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 # License for the specific language governing permissions and limitations
15 # under the License.
16 
17 import tornado.httpserver
18 import tornado.ioloop
19 import tornado.options
20 import tornado.web
21 
22 from tornado.options import define, options
23 
24 define("port", default=8888, help="run on the given port", type=int)
25 
26 
27 class MainHandler(tornado.web.RequestHandler):
28     def get(self):
29         self.write("Hello, world")
30 
31 
32 def main():
33     tornado.options.parse_command_line()
34     application = tornado.web.Application([
35         (r"/", MainHandler),
36     ])
37     http_server = tornado.httpserver.HTTPServer(application)
38     http_server.listen(options.port)
39     tornado.ioloop.IOLoop.current().start()
40 
41 
42 if __name__ == "__main__":
43     main()
View Code

1 从2四、3三、38行能够看出,tornado.options是tornado存放配置文件处理的类架构

2 第27行MainHandler类指定了http的返回内容,是用户定义的返回内容,它继承了tornado.web.RequestHandler。这个类应该是处理http请求的部分,或者说接受用户输入返回内容的部分app

3 从34行能够看出,tornado.web.Application是存放/处理http url部分,我理解一个web应用的全部参数应该都注入到application实例中less

4 从37行能够看出,实例了一个tornado.httpserver.HTTPServer对象,咱们想要的web服务器实现部分就在这里了。ide

5 第39行,这行语句应该是开始处理数据内容,猜想高性能的主要处理部分应该就在这里了。

至于38行的http_server.listen(options.port),就是一个注入参数的问题,我以为分析类的时候应该也能顺便分析到。

 

OK,咱们开工,从helloworld开始撸tornado的源代码。

相关文章
相关标签/搜索