Tornado learning (a)

tornado source package includes some exemplary procedures demos directory, from the point of view a simple code structure tornado helloworld.py application.

Complete example program is as follows:

Copy the code
01    #!/usr/bin/env python
02    #
# 03 Copyright 2009 Facebook
04    #
05     
06    import tornado.httpserver
07    import tornado.ioloop
08    import tornado.options
09    import tornado.web
10     
11    from tornado.options import define, options
12     
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()
Copy the code

 

The first is a set of import. The more normal, of course, before the others or have a comment or something.

1    import tornado.httpserver
2    import tornado.ioloop
3    import tornado.options
4    import tornado.web
5     
6    from tornado.options import define, options

 

Next, it is the option to define the application, so you can specify parameters when launching the application. tornado tornado.options.define provides a method to simplify the customization options parameters can be viewed by specific help. Here are examples of direct define port parameters:

1    define("port", default=8888, help="run on the given port", type=int)

Next is MainHandler settings:

1    class MainHandler(tornado.web.RequestHandler):
2        def get(self):
3            self.write("Hello, Nowamagic")

XXHandler specific implementation for the url mapped.

Handler is defined below main () function:

Copy the code
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()
Copy the code

When the application executes, it will first select the parameter parsing. After you create an Application instance and passed to HTTPServer instance, after starting this instance, this, http server started. tornado.httpserver module is used to support non-blocking HTTP Server.

After starting the server, you also need to start an instance IOLoop, so you can start the event loop mechanism, working with non-blocking HTTP Server. Of course, the specific implementation is quite complex, here is just a quick overview.

 

Guess you like

Origin www.cnblogs.com/wangzhilong/p/12549452.html