Tornado Learning (Four)

Next we look at helloword.py only a handler.

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

It is a subclass of tornado.web.RequestHandler covering get a parent class. get method is also very simple, direct, write a "hello world" string to the client.

Not difficult to think, Tornado when you receive a user request http://127.0.0.1:8888/, we will eventually call the get method of MainHandler. This is the middle through a lot of processes and logic, we will be 11 track and confirm.

Next, look at a main function.

1    http_server = tornado.httpserver.HTTPServer(application)

We looked is a new instance of a http server and in front of the created application as a parameter of structure httpserver constructor. HTTPServer class definition tornado / httpserver.py in. This is obviously the hero. It explanatory notes longer than the Application, need to focus on.

Httpserver the concept of tornadoe, brief summary is down: read http request of the client, the corresponding Handler call, then the function HTTPServer.write data back to the client.

In the comments, the authors cite a simple example to illustrate this concept (do not even need to use participation Handler class):

Copy the code
01    import tornado.httpserver 
02    import tornado.ioloop 
03     
04    def handle_request(request): 
05        message = "You requested %s\n" % request.uri 
06        request.write("HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n%s" % ( 
07                       len(message), message)) 
08        request.finish()
09     
10        http_server = tornado.httpserver.HTTPServer(handle_request) 
11        http_server.listen(8888)
12        tornado.ioloop.IOLoop.instance().start()
Copy the code

See how easy it is not, a handle_request function can prop up a website. Of course, this site features a very simple, but it is the customer's request to write back to it.

You can certainly masterpiece in handler_request function in the article, to execute different code for different url, to achieve the same effect front Handler mechanism, however, tornado has refined this demand a set of very efficient handler mechanism, with up very comfortable. If there is no particular reason, you do not have to go to work, "repeat-create the wheel," the.

This is why we generally call web framework, tornado basic framework has been put in each process of setting up a http server, you only need to fill in the blanks to fill, customization, "decoration" look.

The tornado HTTPServer will be responsible for parsing the user's HTTP Request, constructing a request object. RequestHandler to subsequent processing. Request parsing is a standardized process, the basic need customization. Request for handler (ie RequestHandler) is part of the customer is the focus of.

Analysis of HTTPServer will account for a large space, we left behind a special study. In the analysis helloworld, we just remember, Application and will HTTPServer instance is bound.

1    http_server.listen(options.port)

HTTP is working on the TCP protocol, so it is actually TCPServer derived class. Socket programming had experienced readers will remember, start a TCP server has three essential steps:

  1. create socket to create a socket.
  2. bind address bind address.
  3. listen listening execution.

Achieve TCPServer class of naturally draws on Unix / Linux in socket mechanism. Therefore, it also has the above steps, and these steps are performed in a function call HTTPServer.listen (). Now do not mention these details, we'll sift left behind when analyzing TCPServer this class.

Listen function parameter is the port number, mentioned earlier, the default port number is 8888 tornado demo from helloworld.py first few lines you can see.

1    from tornado.options import define, options 
2    define("port", default=8888, help="run on the given port", type=int) 

is a member of the class OptionParser define functions, as defined in tornado / options.py, the mechanism and the parse_command_line () is similar. The above is the definition of an int variable called port, the default is 8888, but also with a caption, powerful. port variables are stored into the options object of a dictionary members. We can see, access method is options.port. Executing the http_server.listen (options.port), your PC will start a server on this port options.port, the user begins listening for connections.

After reading the previous http_server.listen (), seem to feel anything less points. By the way, do not fall into the accept key function, users connect and how to handle it? Do not worry, that was right. This one looks very iffy thing, in fact, is equivalent to the familiar accept.

1    tornado.ioloop.IOLoop.instance().start()

Why does not directly come to accept? This IOLoop is what?

IOLoop relationship between TCPServer is actually very simple. After the recalled scene TCP server written in C language, we have written a create-bind-listen three-stage, in fact, things have not finished. We have to write code to handle accept / recv / send it. Normally we would write an infinite loop, constantly calls accept to respond to client link. This infinite loop is IOLoop here. These codes allow you to write, and finally they were all similar, so the tornado simply write a set of standard codes, enclosed in IOLoop years.

IOLoop will be responsible accept this step. IOLoop you can comment out this line, then visit http://127.0.0.1:8888/, you will find simply Rom server. By capturing Packet you will find, in fact, the server does not respond to connection requests.

For recv / send operation, usually carried out in a loop, it may be abstracted into IOLoop. When we analyze achieve HTTPServer class will see it is how the aid IOLoop work.

So far we have the web server has a complete.

We enter http://127.0.0.1:8888/ in the browser, the browser will connect to our server, the HTTP request to HTTPServer in. HTTPServer will first parse request, then reqeust to the first match to the Handler. Handler is responsible for organizing data, the API call to send data to the client.

 

Guess you like

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