Deep understanding of Django middleware and djangomiddleware

Source: Internet
Author: User

Deep understanding of Django middleware and djangomiddleware

This article is based on Django 1.11

Summary

Middleware (middleware) in Django is a hooks framework embedded in Django's request/response Processing Mechanism. It is an underlying plug-in system that modifies django's global input and output. We can customize some of the features we want to process user requests.

In Django, middleware is actually a class, which contains a set of specific functions. When a request arrives or ends, django will execute the corresponding methods in the middleware according to the middleware rules we define. The default activated middleware of A Django project can be seen in the configuration of our project:

Settings. py

MIDDLEWARE = ['django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',]

MIDDLEWARE each element in the list is actually a separate MIDDLEWARE. For example: django. middleware. csrf. the middleware CsrfViewMiddleware serves to include csrf_token when submitting a request in the form. Otherwise, it will not be submitted correctly.

The use of middleware also requires a focus on the sequence. The next layer depends on the encapsulation of the previous layer. For example, our AuthenticationMiddleware is an authentication middleware that stores authentication user information in sessions, however, it must be dependent on SessionMiddleware to be used correctly. Therefore, it must be later than SessionMiddleware. For more information about the sequence, see here.

Middleware Structure

The middleware class must contain the following processing methods:

1. process_request (self, request)
2. process_view (self, request, callback, callback_args, callback_kwargs)
3. process_template_response (self, request, response)
4. process_exception (self, request, exception)
5. process_response (self, request, response)

Execution Process

Take the default middleware in our project as an example. The specific process is as follows:

Middleware execution prerequisites

The middleware must be executed layer by layer in a certain order, and specific content must be returned according to the standard:

  • If the value is None, the execution continues in order.
  • If it is an HttpResonse object, the object is directly returned to the user.

There is a difference before and after a version. Please note that:

After Django1.10, when a middleware, such as CsrfViewMiddleware, does not return None for process_request, the request is sent to process_response of CsrfViewMiddleware, that is, it is returned to the middleware of the same layer:

In versions earlier than Django1.10, the underlying middleware is returned:

Middleware method:

1,process_request(self, request)

The request parameter is our HttpRequest object. process_request will be called before each request is determined which view to use. It will return the None or HttpResponse object.

2,process_view(self, request, callback, callback_args, callback_kwargs)

The request parameter is the HttpRequest object, and callback is the view function used by the request. The specific function name of the book is not of the string type. Callback_args and callback_kwargs are parameters required by the view function. They return None or HttpResponse objects.

3,process_template_response(self, request, response)

The request is an HttpRequest object, and the response is a TemplateResponse object returned by Django view or middleware. process_template_response () is called after the view uses render to render a template object, it must return a response object after the render method is executed.

4,process_exception(self, request, exception)

The request parameter is the HttpRequest object, and the exception is the Exception object of raise in the view function. When the view function raise an exception, process_exception is called. It returns the None or HttpResponse object.

5,process_response(self, request, response)

The request is an HttpRequest object, and the response is an HttpResponse or StreamingHttpResponse object returned by django view or middleware. process_response will be called before all responses reach the browser.

Detailed execution process of Middleware

Because process_template_response is called only in a specific rander rendering, this method is not added during the process.

Self-built middleware and execution process test

To clearly display the execution process of the middleware and how to customize a middleware, we simulate a simple user request and middleware execution process:

Custom Middleware

From django. utils. deprecation import MiddlewareMixinclass MyMiddleware_1 (MiddlewareMixin): def process_request (self, request): print ("Custom process_request 1") return None def process_response (self, request, response ): print ("Custom process_response 1") return response def process_view (self, request, callback, callback_args, callback_kwargs): print ("Custom process_view 1 ") return None def process_exception (self, request, exception): print ("Custom process_exception 1") class MyMiddleware_2 (MiddlewareMixin): def process_request (self, request ): print ("Custom process_request 2") return None def process_response (self, request, response): print ("Custom process_response 2") return response def process_view (self, request, callback, callback_args, callback_kwargs): print ("Custom process_view 2") return None def process_exception (self, request, exception): print ("Custom process_exception 2 ")

Introduction

MIDDLEWARE = ['django. middleware. security. securityMiddleware ', 'django. contrib. sessions. middleware. sessionMiddleware ', 'django. middleware. common. commonMiddleware ', 'django. middleware. csrf. csrfViewMiddleware ', 'django. contrib. auth. middleware. authenticationMiddleware ', 'django. contrib. messages. middleware. messageMiddleware ', 'django. middleware. clickjacking. XFrameOptionsMiddleware ', 'app01. middle_by_me.MyMiddleware_1 ', # The first custom middleware 'app01. middle_by_me.MyMiddleware_2 '# Second custom middleware]

Output result

Custom middleware application scenarios

In fact, the application scenario is not very fixed, because the requirements in the actual use process are different, so let me give you a simple example that I can think.

Without modifying the source code of the business logic, I can use middleware to filter user access or control access. Even more awesome operations can be considered: When the Origin Site CDN, the request passes through the origin site, and middleware determines whether the requested content is in the cache. If the requested content is directly returned in the cache, is it cool without going through the Business backend logic ~

Isn't it like a decorator for all view functions ~~

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

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.