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

时间:2023-03-10 01:43:19
tornado架构分析1  从helloworld分析tornado架构

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

软件版本:tornado 4.5.2 stable

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

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

我的基础:具备python编程基础,了解http原理及包结构,了解一些常用包及用法。能看懂一些python语法

来吧,开始:

 #!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License. import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web from tornado.options import define, options define("port", default=8888, help="run on the given port", type=int) class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world") def main():
tornado.options.parse_command_line()
application = tornado.web.Application([
(r"/", MainHandler),
])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start() if __name__ == "__main__":
main()

1 从24、33、38行可以看出,tornado.options是tornado存放配置文件处理的类

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

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

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

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

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

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