Django analyzes the entire process from one request to the response at the underlying layer, and django analyzes the response at the underlying layer.

Source: Internet
Author: User

Django analyzes the entire process from one request to the response at the underlying layer, and django analyzes the response at the underlying layer.

As we all know, all Web applications are essentially a socket server, and the user's browser is a socket Client.

#!/usr/bin/env python#coding:utf-8   import socket   def handle_request(client):    buf = client.recv(1024)    client.send("HTTP/1.1 200 OK\r\n\r\n")    client.send("Hello, Seven")   def main():    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 above Code uses socket to implement its essence. For all python web programs, it is generally divided into two parts: server programs and applications. The server program encapsulates the socket server and sorts the request data when the request arrives. The application is responsible for specific logic processing. In order to facilitate application development and avoid repeated wheel creation, some people have invented the related tool-Web framework, for example: Django, Flask, web. py and so on. Different frameworks may adopt different directory structures, but in any case, the developed applications must work with the server program to provide services for users. In the past, how to select a suitable Web application framework became a problem for beginners of Python. This is because, in general, the selection of Web application frameworks limits the selection of available Web servers, and vice versa. At that time, Python applications were generally designed for one of CGI, FastCGI, and mod_python, or even for custom API interfaces of specific Web servers.

PythonWeb Server Gateway Interface (WSGI) is an Interface between a Python application or framework and a Web Server. It has been widely accepted, it has basically achieved its portability goals.

WSGI has no official implementation, because WSGI is more like a Protocol. As long as these protocols are followed, WSGI applications can run on any Server, and vice versa. The django web framework we want to talk about today requires wsgi. djano does not implement socket internally, but is implemented through socket. Overview:

The process from Django's request to response is simply to use wsgi. When the user sends a request for response, the request_started signal is sent before the response, and the middleware process_request, after the response is complete, process_response of the middleware is called.

1. a browser user sends a request using a url

When the django program is started:

Source code:

(Note: Here is the project name. wsgi. application, and the project name created by the blogger is s3 .)

Execute the function corresponding to applicaion:

Source code:

Next let's look at the get_wsgi_application function:

Source code:

From the source code above, we can see that django returns a WSGIHandler class instance for every request response.

Source code of WSGIHandler class:

 

Here, we need to pay attention to the following:

Load_middleware is called only for the first request, that is, the loading of middleware is only executed during the first request.

The request_started signal is sent in the WSGIhandler class.

Next, let's first take a look at his parent class base. BaseHandler class:

Base. BaseHandler class source code:

 

Complete execution flowchart of middleware:

Note: it can be seen that:

  • When the request arrives, it will first go through the middleware Process_Request. If Process_Request has return, that is, the current url is not passed through the middleware, the program will jump directly to the last Process_Response, and then execute all Process_Response in reverse order.
  • Then the program will enter the url. At this time, the program will check whether the user has set process_view. If so, execute process_view first. If process_view has return, the program will jump directly to the last Process_Response, then execute all Process_Response in reverse order.
  • If the previous step does not contain process_view, the program will execute the function in the views file.
  • After the previous step is executed, the program checks whether an exception occurs. If yes, the process_exception corresponding to the middleware class is executed first.
  • Finally, the program executes all Process_Response in reverse order.

Note: request_middleware and view_middleware are executed sequentially. template_response_middleware, response_middleware, and prediction_middleware are executed in reverse order.

Url:

First, the program will:

Source code:

(This is also the project name. urls)

Find the urls. py file

Url matching source code:

Whether the current url belongs to the LocaleRegexURLResolver class is directly used here.

LocaleRegexURLResolver class:

Pre-Compilation:

Regular Expression matching:

We need to pay attention to the resolve method of the LocaleRegexURLResolver class:

Note: self. url_patterns is all regular URLs. Here, the regular url is cyclically; new_path is the url entered by the user. Here pattern. resolve is the resolve method for executing the RegexURLPattern class:

From the source code above, we can see that the resolve method of the RegexURLPattern class performs a specific matching operation through regex. search, where regex encapsulates the re module.

The url we define:

Sample Code:

from django.conf.urls import urlfrom django.contrib import adminfrom APP01 import viewsurlpatterns = [    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 code url:

From the source code above, we can see that the url method receives the Regular Expression and view parameters, and finally returns a RegexURLPattern object. The RegexURLPattern class further processes the Regular Expression and view.

 

As can be seen from the source code above, after completing regular expression matching, view will be run as a callback function. This explains how the url is bound to the views function.

Next, the program calls the views function, renders the template, and returns to the view. If the program has no exceptions, execute Process_Response of the middleware (For details, refer to the execution process of the middleware above ), the program sends a signal request_finished, and the events that subscribe to this signal are cleared and any resources in use are released.

If you think this article is of reference value to you, you are welcome to help the bloggers click the recommendation below the article. Thank you!

Related Article

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.