Python - Django - Middleware process_exception

process_exception (self, request, exception) function takes two parameters, exception the Exception object is generated in view of the exception

Process_exception function execution order is performed in reverse order settings.py set middleware

Process_exception function when abnormality occurs only in the view function was executed, it returns the value can be None, or may be a HttpResponse object

If the return None, the method continues to the next intermediate process_exception to handle exceptions

If the return HttpResponse, calls the method middleware process_response

middleware_test.py:

Import MiddlewareMixin django.utils.deprecation from 
from django.shortcuts Import HttpResponse 


class the Test (MiddlewareMixin): 
    DEF process_request (Self, Request): 
        Print ( "It is a middleware -> the Test") 

    DEF process_exception (Self, Request, Exception ): 
        Print ( "this is the Test of process_exception") 
        Print (Exception) 


class test2 (MiddlewareMixin): 
    DEF process_request (Self, Request): 
        Print ( "it is a middleware -> test2") 

    DEF process_exception (Self, Request , Exception): 
        Print ( "here is the process_exception Test2") 
        Print (Exception)

views.py:

django.shortcuts Import HttpResponse from 


DEF index (Request): 
    Print ( "This is the index page") 
    The raise ValueError ( "This is a mistake") 
    return HttpResponse ( "Here is the main page index")

Visit, http: //127.0.0.1: 8000 / index /

 

operation result:

 

Guess you like

Origin www.cnblogs.com/sch01ar/p/11517128.html