最近公司須要我寫一個高性能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()
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的源代碼。