[Django] Django handles request process details

Source: Internet
Author: User

First, some other things related to Django (preparations) are as follows:

  • If Apache/mod_python provides services, the request is sent to the Django. Core. Handlers. modpython. modpythonhandler instance created by mod_python to Django.
  • If it is another server, it must be compatible with wsgi. In this way, the server will create a Django. Core. Handlers. wsgi. wsgihandler instance.

Both classes are inherited from Django. Core. Handlers. Base. basehandler, which contains the public code required for any type of request.

Prepare a processor (handler)

After one of the above processors is instantiated, a series of things happen:

  1. This processor (handler) imports your Django configuration file.
  2. This processor imports the custom exception class of Django.
  3. This processor calls its own load_middleware method, loads all the middleware classes in the middleware_classes, and saves them internally.

The last one is a bit complicated. Let's take a closer look.

A middleware class can penetrate into four stages of the processing process: request, view, response, and exception. To do this, you only need to define the specified and appropriate methods: process_request, process_view, process_response, and process_exception. Middleware can define any or all of these methods, depending on what features you want it to provide.

When there is middleware in the processor, it searches for the method named above and creates four lists as the processor instance variables:

  • _ Request_middleware is a list of stored process_request methods (in each case, they are real methods and can be called directly). These methods come from any middleware class that defines them.
  • _ View_middleware is a list of methods for saving process_view. These methods come from any middleware class that defines them.
  • _ Response_middleware is a list of stored process_response methods. These methods come from any middleware class that defines them.
  • _ Exception_middleware is a list of methods for saving process_exception. These methods come from any middleware class that defines them.
Httprequest is ready to go to Django

Now that the processor is ready to actually start processing, it sends a signal to the scheduler request_started (the scheduling program inside Django allows different components to declare what they are doing, you can also write code to listen to specific events. There is no official documentation for this, but there are some comments on the Wiki .). Next, it instantiate a subclass of Django. http. httprequest.

Different Processors may be an instance of Django. Core. Handlers. modpython. modpythonrequest, or an instance of Django. Core. Handlers. wsgi. wsgirequest. Two different classes are required because mod_python and wsgi APIs pass in request information in different formats. This information needs to be parsed into a separate standard format that Django can process.

Once an httprequest or something similar exists, the processor calls its own GET_RESPONSE method and passes in this httprequest as a unique parameter. This is where almost all real activities occur.

Middleware is working.

The first thing GET_RESPONSE does is to traverse the _ request_middleware instance variable of the processor and call every method. The httprequest instance is passed as the parameter.

for middleware_method in self._request_middleware:response = middleware_method(request)if response:    break

These methods can be used to process the remaining short circuit and immediately let GET_RESPONSE return, by returning a value of its own (if they do so, the return value must be Django. HTTP. an instance of httpresponse, which will be discussed later ). If one of them does this, we will immediately return to the master processor code. GET_RESPONSE will not wait to see what other middleware classes want to do, it will return directly, and then the processor enters the response stage.

However, in general, the middleware method applied here simply performs some processing and determines whether to add, delete, or supplement the request attributes.

URL resolver Parsing

Assuming that no middleware acting on the request directly returns response, the processor will try to parse the request URL in the next step. It looks for a configuration named root_urlconf in the configuration file, and adds the root URL/to this configuration as a parameter to create Django. core. urlresolvers. an instance of regexurlresolver, and then calls its resolve method to parse the request URL path.

URL resolver follows a fairly simple pattern. For each entry in the urlpatterns list generated in the URL configuration file based on the configuration of root_urlconf, it checks whether the URL path matches the regular expression of the entry, if yes, there are two options:

  1. If this entry has an include and resolver that can be called to intercept the matched URL, go to the URL configuration file specified by include, and start to traverse each entry in the urlpatterns list. Depending on the depth and adequacy of your url, this may be repeated several times.
  2. Otherwise, resolver returns three entries:
    • The view function specified by the matched entry;
    • An unnamed match group obtained from the URL (used as the location parameter of the View );
    • A Dictionary of key-word parameters, which is composed of any name matching group obtained from the URL and any other key-word parameters obtained from urlconf.

Note that this process will stop when the first view entry is matched, so it is best to make your url configuration transition from complex regular expressions to simple regular expressions, this ensures that the resolver does not first match the simple one and returns the wrong view function.

If no matching entry is found, resolver will generate the Django. Core. urlresolvers. resolver404 exception, which is a subclass of Django. http. http404 exception. Later we will know how it is handled.

Once you know the required view function and related parameters, the processor will view its _ view_middleware list and call the method to pass in httprequst, view function, the location parameter list and keyword parameter dictionary for this view.

Also, middleware may intervene in this phase and force the processor to return immediately.

View

If the processing process continues at this time, the processor will call the view function. Views in Django are not strict because they only need to meet the following conditions:

  • Must be called.
  • The instance of Django. http. httprequest must be accepted as the first value parameter.
  • You must be able to generate an exception or return an instance of Django. http. httpresponse.

You can leave it empty. However, in general, views uses Django's database API to create, retrieve, update, and delete database items, and loads and renders a template to present some things to the end user.

Template

Django's template system has two parts: one is the HTML used by designers to mix a small amount of other things, and the other is to use pure python for programmers.

From the perspective of an HTML author, Django's template system is very simple and requires only three structures:

  • Variable reference. In the template, it is as follows: {Foo }}.
  • Template filtering. In the preceding example, the following is used to filter the vertical bars: {Foo | bar }}. This is usually used to format the output (for example, run textile and format the date ).
  • Template tag. Yes: {% Baz % }. This is where the "logic" of the template is implemented. You can {% if Foo %}, {% for bar in Foo %}, and so on. If and for are both template labels.

Variable references work in a very simple way. If you only want to print the variable, as long as {Foo}, the template system will output it. The only complex case here is {Foo. Bar}. At this time, the template system tries several things in order:

  1. First, it tries a dictionary search to see if Foo ['bar'] exists. If it exists, its value is output, and the process ends.
  2. If the dictionary search fails, the template system tries the attribute search to see if Foo. Bar exists. At the same time, it also checks whether this attribute can be called. If yes, it is called.
  3. If the attribute search fails, the template system tries to use it as a list index.

If all of these failed, the template_string_if_invalid value is configured in the template system output. The default value is a null string.

Template filtering is a simple Python function. It accepts a value and a parameter and returns a new value. For example, date filtering uses a python datetime object as its value, a standard strftime formatting string as its parameter, and returns the result after the formatted string is applied to the datetime object.

The template tag is used in a bit of complicated things. It is the place where you know how Django's template system actually works.

Django template Structure

Internally, A Django template is embodied as a "nodes" set, which are inherited from the basic Django. template. node class. Nodes can perform various processing, but there is one thing in common: each node must have a method called render, which accepts the second parameter (the first parameter is obviously a node instance) is Django. template. an instance of context, which is a dictionary-like object that contains all the variables available in the template. Node's render method must return a string, but if node's work is not output (for example, it is to be added by adding, delete or modify the variables in the input context instance variables to modify the template context), you can return an empty string.

Django contains many node subclasses to provide useful functions. For example, each built-in template label is processed by a node subclass (for example, ifnode implements the If label, fornode implements the for label, and so on ). All built-in labels can be found in Django. template. defaulttags.

In fact, all the template structures described above are in some form of nodes, and there is no exception in plain text. Variable Search is processed by variablenode. For the sake of nature, filtering is also applied to variablenode. The tag is a variety of nodes, and text is a textnode.

Generally, rendering a template with a view takes the following steps:

  1. Load the template to be rendered. This is done by Django. template. loader. get_template. It can use any of these methods to locate the required template file. The get_template function returns a Django. template. template instance, which contains the parsed template and the method used.
  2. Instantiate a context to render the template. If the sub-class Django. template. requestcontext of context is used, the attached context processing function automatically adds variables not defined in view. The context builder method uses a key/value pair (for a template, it will be changed to a name/value variable) as its unique parameter, requestcontext uses an instance of httprequest and a dictionary.
  3. Call the render method of the template instance. The context object is used as the first location parameter.

The Return Value of the template render method is a string, which is composed of the values returned by all nodes render methods in the template. The call sequence is the order in which they appear in the template.

A little bit about response

Once a template is rendered or other suitable outputs are generated, view generates a Django. http. httpresponse instance. Its builder accepts two optional parameters:

  • A string that acts as the response body (it should be the first position parameter, or the keyword parameter content ). Most of the time, this will be used to render the output of a template, but it is not necessary. Here you can input any valid Python string.
  • As the value of the Content-Type Header of response (it should be the second position parameter, or the keyword parameter mine_type ). If this parameter is not provided, Django will use the default_mime_type value in the configuration and the default_charset value. If you have not changed them in the Django global configuration file, they are "text/html" and "UTF-8 ".
Exception

If an exception occurs in the view function or something, GET_RESPONSE (I know we have spent some time exploring views and templates, but once the view returns or an exception occurs, we will continue to refresh the GET_RESPONSE method in the middle of the processor) will traverse its _ prediction_middleware instance variables and call each method there, passing in httpresponse and this exception as the parameter. If successful, one of these methods will instantiate an httpresponse and return it.

At this time, there may still be no httpresponse, which may be due to several reasons:

  • View may not return values.
  • View may have an exception, but no middleware can handle it.
  • When a middleware method tries to handle an exception, it generates a new exception.

At this time, GET_RESPONSE will return to its own exception handling mechanism, which has several levels:

  1. If exception is http404 and debug is set to true, GET_RESPONSE executes view Django. Views. Debug. technical_404_response and passes in httprequest and exception as parameters. This view displays the pattern information that the URL resolver tries to match.
  2. If debug is false and the exception is http404, GET_RESPONSE will call the resolve_404 method of URL resolver. This method is used to view the URL configuration to determine which view is specified to handle the 404 error. The default value is Django. Views. defaults. page_not_found. However, you can assign a value to the handler404 variable in the URL configuration.
  3. If debug is set to true for any other type of exception, GET_RESPONSE executes view Django. Views. Debug. technical_500_response and passes in httprequest and exception as parameters. This view provides detailed information about exceptions, including traceback, local variables in each layer stack, detailed descriptions of httprequest objects, and lists of all invalid configurations.
  4. If debug is false, GET_RESPONSE will call the resolve_500 method of URL resolver, which is very similar to the resolve_404 method. In this case, the default view is Django. views. defaults. server_error, but you can assign a value to the handler500 variable in the URL configuration.

In addition. HTTP. if any exception occurs outside of http404 or Python's built-in systemexit, the processor will send a got_request_exception signal to the dispatcher and construct a description about the exception before returning the exception, send it to everyone listed in the admins configuration of the Django configuration file.

Now, no matter at which level the GET_RESPONSE encounters an error, it returns an httpresponse instance, so we return to the main part of the processor. Once it obtains an httpresponse, the first thing it does is to traverse its _ response_middleware instance variable and apply the method there, passing in httprequest and httpresponse as parameters.

Note that this is the last opportunity for any middleware that you want to change.

Once the middleware completes the final step, the processor sends the request_finished signal to the dispatcher. This is the final call for anything that you want to execute in the current request. The handler that listens to this signal clears and releases any resources in use. For example, the Django request_finished listener closes all database connections.

After this happens, the processor will construct a suitable return value and return anything to instantiate it (now, it is an appropriate mod_python response or a wsgi compatible response, depending on the processor) and return.

This is how Django processes a request.

 

[Django] Django processes the request process details (to be transferred)

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.