The entire process of one request to the response

Source: Internet
Author: User

The entire process of one request to the response

As we all know, the Web application is essentially a socket server, and the user's browser is a socket client.

12345678910111213141516171819202122 #!/usr/bin/env python#coding:utf-8   importsocket   defhandle_request(client):    buf = client.recv(1024)    client.send("HTTP/1.1 200 OK\r\n\r\n")    client.send("Hello, Seven")   defmain():    sock =socket.socket(socket.AF_INET, socket.SOCK_STREAM)    sock.bind((‘localhost‘,8000))    sock.listen(5)       while True:        connection, address =sock.accept()        handle_request(connection)        connection.close()   if__name__ ==‘__main__‘:    main()

The code above uses the socket to achieve its essence, and for all Python Web applications it is generally divided into two parts: server programs and Applications. The server program is responsible for encapsulating the socket server and collating the requested data when the request arrives. The application is responsible for the specific logical processing. In order to facilitate the development of the application, to avoid the repetition of the wheel, so someone invented the relevant tool--web framework, for Example:django, Flask, web.py and so on. Different frameworks may have different directory structures, but in any case, the applications you develop will have to work with the server program to provide services to the user. Previously, how to choose the right Web application framework became a problem for Python beginners because, in general, the choice of Web application framework would limit the choice of available Web servers and vice versa. At that time, Python applications were typically designed for one of the Cgi,fastcgi,mod_python, even for a custom API interface for a particular Web server.

The Pythonweb server Gateway interface (Python Web server, Gateway Interface, abbreviated as WSGI) is an interface between a Python application or a framework and a WEB server that has been widely accepted, It has basically reached its goal of portability.

WSGI no official implementation, because WSGI is more like a protocol.  The WSGI application (application) can run on any server (server), and vice versa, as long as these protocols are followed. The Django Web framework we're going to talk about today needs to use the Wsgi,djano inside without implementing a socket, but through a socket. Overview:

The Django request to the response process, simply to use WSGI, when the user sent a request to response, before the response to send request_started signal, through the process_request of the middleware, The process_response of the middleware is called when the response is complete.

1. browser-side user sent a request with a URL

When the Django program starts, it is based on the settings:

Source:

(Note: Here is project name. Wsgi.application, the blogger creates project named S3. )

Perform the applicaion corresponding function:

Source:

Next we look at the Get_wsgi_application function:

Source:

From the source above, it can be seen that Django each request response will return an instance of the Wsgihandler class.

Wsgihandler class Source:

Here, we need to focus on:

Load_middleware only the first request is invoked, that is, the loading of the middleware will only be performed on the first request.

The request_started signal is sent in the Wsgihandler class.

Let's start by focusing on his parent class base. Basehandler class:

Base. Basehandler class Source:

Complete implementation process diagram for middleware:

Note: It can be seen from:

    • When the request arrives, it passes through the process_request of the middleware first, if Process_request has return that the current URL does not pass through the middleware, the program jumps directly to the last Process_response, Then all the process_response are executed in reverse order.
    • Then the program will enter the URL, then the program will detect whether the user has set Process_view, if there is, then the next execution Process_view, if Process_view has return, then the program jumps directly to the last Process_ Response, then executes all process_response in reverse order.
    • If there is no process_view in the previous step, the program executes the functions in the views file
    • After performing the previous step, the program detects that there are no anomalies, and if so, executes the corresponding process_exception of the middleware class first.
    • Finally, the program executes all the process_response in reverse order.

Note: Request_middleware, view_middleware are sequential execution, Template_response_middleware, Response_middleware, Exception_ Middleware is reverse-order execution.

Url:

First the program will be based on the configuration file:

Source:

(again this is Project name. URLs)

Locate urls.py File

URL Matching source code:

This is where the current URL is directly used by the Localeregexurlresolver class.

Localeregexurlresolver class:

Pre-compilation:

Regular match:

What we need to focus on is the resolve method of the Localeregexurlresolver class:

Note: Self.url_patterns is the regular URL, where the regular URL is looped, and New_path is the user-entered URL, where Pattern.resolve is the resolve method that executes the Regexurlpattern class:

By the above source can be seen Regexurlpattern class resolve method is through Regex.search for specific matching operations, where the Regex encapsulates the re module.

We define the URL:

Example code:

12345678910 fromdjango.conf.urls importurlfrom django.contrib importadminfromAPP01 importviewsurlpatterns =[    url(r‘^admin/‘, admin.site.urls),    url(r‘^articles/(?P<year>[0-9]{4})/$‘, views.special_case_2003),    url(r‘^articles/([0-9]{4})/$‘, views.year_archive),    url(r‘^articles/([0-9]{4})/([0-9]{2})/$‘, views.month_archive),    url(r‘^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$‘, views.article_detail),]

Source URL:

From the above source can be seen in the URL method to receive the regular expression and view two parameters, and eventually return a Regexurlpattern object, Regexurlpattern class to the regular expression and view for further processing

As can be seen from the source code above, when the regular match is completed, the view is run as a callback function. This explains how the URL is bound to the views function.

Next, the program calls the views function, and renders the template, and returns to the view, if the program does not have an exception, the implementation of the middleware process_response (see the implementation process of the above middleware), the final program sends a signal request_finished signal, Events that subscribe to this signal will empty and free any resources that are in use.

If you think this article to you have reference value, Welcome to help Bo Master click on the recommendation under the article, thank you!

The entire process of one request to the response

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.