首页 > 技术文章 > Tornado 高并发源码分析之一---启动一个web服务

hepingqingfeng 2017-04-01 13:50 原文

 

前言: 启动一个tornado 服务器基本代码

 

 1 class HomeHandler(tornado.web.RequestHandler): #创建 RequesHandler 对象,处理接收到的 http 请求
 2 def get(self):
 3      entries = self.db.query("SELECT * FROM entries ORDER BY      published DESC LIMIT 5")
 4      if not entries:
 5          self.redirect("/compose")
 6          return
 7         self.render("home.html", entries=entries)
 8  
 9 class Application(tornado.web.Application): #创建 Application 对象, 定义 setting 和 URL 映射规则
10      def __init__(self):
11        handlers = [
12             (r"/", HomeHandler),
13             (r"/archive", ArchiveHandler),
14         ]
15        settings = dict(
16        blog_title=u"Tornado Blog",
17        template_path=os.path.join(os.path.dirname(__file__),    "templates"),
18        static_path=os.path.join(os.path.dirname(__file__), "static"),
19        ui_modules={"Entry": EntryModule},
20        xsrf_cookies=True,
21        debug=True,
22        )
23       tornado.web.Application.__init__(self, handlers, **settings) #将参数设置传递到父类 Application中
24  
25  
26 def main():
27       http_server = tornado.httpserver.HTTPServer(Application()) #传递 Application 对象,封装成 HTTPServer 对象
28       http_server.listen(8000) #启动 HTTPServer 监听,实际上    HTTPServer 继承自 TCPServer,是在TCPServer 中启动 listen Socket 端口
29       tornado.ioloop.IOLoop.instance().start() 获取全局IOLoop 单例,启动IOLoop 大循环

 

 
 

 

推荐阅读