Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Django Middleware

Django Middleware

Django middleware is a hook that modifies Django request or response objects; it can be understood as a processing step between HttpRequest and HttpResponse handling.

In the process from request to response in the browser, Django needs to process through many middleware components, as shown in the following figure:

Functions of Django middleware:

Middleware components are configured in the MIDDLEWARE option list in the settings.py file.

Each string option in the configuration is a class, that is, a piece of middleware.

Django's default middleware configuration:

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'

,

]

Custom middleware

Middleware can define four methods, namely:

process_request

(

self

,

request

)

process_view

(

self

,

request

,

view_func

,

view_args

,

view_kwargs

)

process_exception

(

self

,

request

,

exception

)

process_response

(

self

,

request

,

response

)

Steps to customize middleware:

Create a new py file in the app directory with a custom name, and import MiddlewareMixin in that py file:

from django.utils.deprecation import MiddlewareMixin

The custom middleware class should inherit from the parent class MiddlewareMixin:

class MD1(MiddlewareMixin): 

    pass

Register the custom middleware class in MIDDLEWARE in 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'

,

   

   

'app01.middlewares.MD1'

,

]


Methods of the custom middleware class

The methods of the custom middleware class are: process_request and process_response.

process_request method

The process_request method has one parameter, request, which is the same as the request in the view function.

The return value of the process_request method can be None or an HttpResponse object.

The process_request method is executed before the view function.

When multiple middleware components are configured, they are executed in order according to their registration order in MIDDLEWARE, that is, the list index values.

The request parameter passed between different middleware components is the same request object.

Example

from

django.

utils

.

deprecation

import

MiddlewareMixin

from

django.

shortcuts

import

render

,

HttpResponse

class

MD1

(

MiddlewareMixin

)

:

   

def

process_request

(

self

,

request

)

:

       

print

(

"md1 process_request method."

,

id

(

request

)

)

# Executed before the view

process_response

The process_response method has two parameters, one is request and one is response; request is the request object, response is the HttpResponse object returned by the view function. This method must have a return value, and it must be response.

The process_response method is executed after the view function.

When multiple middleware components are configured, they are executed in reverse order according to their registration order in MIDDLEWARE, that is, the list index values.

Example

class

MD1

(

MiddlewareMixin

)

:

   

def

process_request

(

self

,

request

)

:

       

print

(

"md1 process_request method."

,

id

(

request

)

)

# Executed before the view

   

def

process_response

(

self

,

request

,

response

)

: :

# Based on request and response

       

print

(

"md1 process_response method!"

,

id

(

request

)

)

# After the view

       

return

response

As shown in the figure below, under normal circumstances execution follows the green route; supposeMiddleware 1has a return value, then it follows the red route, directly executing the process_response method under this class and returning, and the other middleware after it will not be executed.

process_view

The process_view method format is as follows:



process_view(request, view_func, view_args, view_kwargs)

The process_view method has four parameters:

Neither view_args nor view_kwargs includes the first view parameter (request).

The process_view method is executed before the view function and after the process_request method.

The return value can be None, view_func(request), or an HttpResponse object.

Example

class MD1(MiddlewareMixin):
    def process_request(self, request):
        print("md1 process_request method.", id(request)) # Executed before the view


    def process_response(self,request, response): :# Based on request and response
        print("md1 process_response method!", id(request)) # After the view
        return response


    def process_view(self,request, view_func, view_args, view_kwargs):
        print("md1 process_view method!") # Executed before the view, in order
        #return view_func(request)

process_exception

The process_exception method is as follows:

process_exception(request, exception)

Parameter Description:

The process_exception method is only executed when an exception occurs in the view function, and is executed in reverse order of registration in settings.

Executed after the view function and before the process_response method.

The return value of the process_exception method can be None or an HttpResponse object.

If the return value is None, the page will report a 500 status code error and the view function will not be executed.

The process_exception method is executed in reverse order, and then the process_response method is executed in reverse order.

If the return value is an HttpResponse object, the page will not report an error and the status code returned is 200.

The view function is not executed, and the subsequent process_exception methods of this middleware are not executed either; execution starts directly from the process_response method of the last middleware in reverse order.

If the process_view method returns a view function and the view function is executed in advance and reports an error, then regardless of the return value of the process_exception method, the page will report an error, and neither the view function nor the process_exception method will be executed.

Start executing in reverse order directly from the process_response method of the last middleware:

Example

class MD1(MiddlewareMixin):
    def process_request(self, request):
        print("md1 process_request method.", id(request)) # Executed before the view

    def process_response(self,request, response): :# Based on request and response
        print("md1 process_response method!", id(request)) # After the view
        return response

    def process_view(self,request, view_func, view_args, view_kwargs):
        print("md1 process_view method!") # Executed before the view, in order
        #return view_func(request)


    def process_exception(self, request, exception):# This method is only triggered when an error is raised
        print("md1 process_exception method!")
        # return HttpResponse(exception) # Return error information

- request is the HttpRequest object. - exception is the Exception object generated by an exception in the view function.