Detailed Explanation of Basic Usage of Django Middleware

  • 2021-07-22 10:47:58
  • OfStack

Preface

django middleware can be executed before the execution of the view function, such as login verification, log recording, etc. The following brief description of the basic usage of the middleware under 1, mainly for the notes of the author when learning

1. Create a folder for middleware functions under the django project folder

The name of the folder can be customized. This article uses utils as the folder name

2. Create the middleware py file in the utils folder

Such as middleware loginCheck. py for login authentication


from django.http import HttpResponseRedirect
from django.utils.deprecation import MiddlewareMixin

class UserLoginCheck(MiddlewareMixin):
  '''
   Login authentication middleware 
  '''
  def process_request(self, request):
    #  Users request Before request 
    path = ['/login/', '/logout/'] #  Object that does not require login detection url
    if request.path in path:
      return

    userinfoSession = request.session.get('userinfo')
    if not userinfoSession:
      return HttpResponseRedirect('/login/')
    return

3. Configure middleware

Configure middleware in setting. py file


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',
  'utils.loginCheck.UserLoginCheck', #  Custom middleware here 
]

Expand

Five Definable Methods of Middleware

Request preprocessing function: process_request (self, request)

This method is timed after Django receives request, but URL has not been parsed to determine which view function should be run. Django passes it the corresponding Request object for modification in the method. If None is returned, Django will continue to process the request, execute the subsequent middleware, and then call the corresponding view. If an HttpResponse object is returned, Django will no longer execute any middleware other than process_response and the corresponding view, and Django will immediately return the HttpResponse.

View preprocessing function: process_view (self, request, callback, callback_args, callback_kwargs)

This method is called after Django executes the request preprocessing function and determines the view (that is, the callback parameter) to be executed, but before the view function actually executes. request: HttpRequest object. callback: Django will call the python function that handles request. This is the actual function object itself, not the function name expressed in a string. args: The list of positional parameters that will be passed into view, but does not include the request parameter (which is usually the first parameter passed into view). kwargs: The keyword parameter dictionary that will be passed into view. process_view () should return an None or HttpResponse object. If None is returned, Django continues to process the request, executes the subsequent middleware, and then calls the corresponding view. If an HttpResponse object is returned, Django will no longer execute any other middleware (regardless of type) and the corresponding view, and Django will return immediately.

Template template rendering function: process_template_response ()

The default does not execute, only in the view function return result object has the render method will execute, and returns the object render method return value to the user (note does not return the view function return result, but returns the view function return value (object) in the rende method result)

Exception post-processing function: process_exception (self, request, exception)

This method is only called if there is a problem with request processing and the view function throws an uncaught exception. This hook can be used to send error notifications, output site-related information to log files, or even try to recover automatically from errors. The parameters of this function include the actual exception object exception thrown by the view function in addition to the 1-pass request object. process_exception () should return an None or HttpResponse object. If None is returned, Django continues to process the corresponding request with the built-in exception handling mechanism of the framework. If an HttpResponse object is returned, Django uses the response object and shorts the built-in exception handling mechanism of the framework.

Response post-processing function: process_response (self, request, response)

This method is called after Django executes the view function and generates response. The processor can modify the contents of response; One common use is content compression, such as the HTML page requested by gzip. The parameters of this method are fairly straightforward: request is an request object, and response is an response object returned from view. process_response () must return an HttpResponse object. This response object can be the original (usually modified) object passed into the function, or it can be newly generated.

Related articles: