Know tornado (1) and tornado (
The demos directory in the tornado source code package contains some sample programs. The simplest helloworld. py shows the code structure of a tornado application.
The complete instance program is as follows:
01 #!/usr/bin/env python02 #03 # Copyright 2009 Facebook04 #05 06 import tornado.httpserver07 import tornado.ioloop08 import tornado.options09 import tornado.web10 11 from tornado.options import define, options12 13 define("port", default=8888, help="run on the given port", type=int)14 15 16 class MainHandler(tornado.web.RequestHandler):17 def get(self):18 self.write("Hello, Nowamagic")19 20 21 def main():22 tornado.options.parse_command_line()23 application = tornado.web.Application([24 (r"/", MainHandler),25 ])26 http_server = tornado.httpserver.HTTPServer(application)27 http_server.listen(options.port)28 tornado.ioloop.IOLoop.instance().start()29 30 31 if __name__ == "__main__":32 main()
The first is a set of import. This is normal again. Of course, there are still comments and things to be commented out.
1 import tornado.httpserver2 import tornado.ioloop3 import tornado.options4 import tornado.web5 6 from tornado.options import define, options
Next, define the application options, so that you can specify some parameters when starting the application. Tornado provides the method tornado. options. define to simplify the definition of the Option parameter. You can view the details through help. Here is a direct example to define port parameters:
1 define("port", default=8888, help="run on the given port", type=int)
Next is the settings of MainHandler:
1 class MainHandler(tornado.web.RequestHandler):2 def get(self):3 self.write("Hello, Nowamagic")
XXHandler implements the ing url.
The following is the definition of the main () function:
1 def main():2 tornado.options.parse_command_line()3 application = tornado.web.Application([4 (r"/", MainHandler),5 ])6 http_server = tornado.httpserver.HTTPServer(application)7 http_server.listen(options.port)8 tornado.ioloop.IOLoop.instance().start()
When the application is executed, the selection parameters are parsed. Create an Application instance and pass it to the HTTPServer instance. Then, start the instance. Then, the http server starts. The tornado. httpserver module is used to support non-blocking HTTP servers.
After starting the Server, you also need to start the IOLoop instance to enable the event Loop Mechanism and work with the non-blocking HTTP Server. Of course, the specific implementation is still complicated. Here is just a brief summary.
Understanding tornado (1)
Understanding tornado (2)
Understanding tornado (3)
Understanding tornado (4)
Understanding tornado (5)
Source: http://www.nowamagic.net/academy/detail/1332566