Django middleware framework MiddleWare

Django middleware in a lightweight, underlying plug-in system, can intervene Django request and response process, modifying the input or output Django.
Middleware is designed to provide a non-intrusive way for developers to develop and enhance the robustness of the Django framework.
We can use middleware to intervene input or output at different stages of processing Django view.

In fact, the principle of middleware is the definition of a decorator, but the decorator can decorate all methods throughout the project;

We can middleware, the object request and response objects corresponding operator intervention.

Middleware implementation process:

1. File a written application in the child middleware.py

DEF my_middleware (get_response was):
     Print ( ' intermediate initialization ' )
     DEF middlewraer (Request, * args, ** kwargs):
         Print ( ' request to intervene before execution ' )
         # were added intervening code, the main application black whitelist list 
        IF request.META [ ' the uSER ' ] == ' KG ' :
             return the HttpResponse ( ' the user can not access ' ) 
        RET = get_response was (Request, * args, ** kwargs)
         Print ( ' after performing intervention response')
        return ret
    return middlewrae

2. Register middleware setting 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',
   # 注册中间件
'users.middleware.my_middleware', ]

Note: Django running in debug mode, middleware init some of them might be called twice.

Multiple middleware implementation process:

1. middleware MIDDLEWARE list setting file will be in reverse order, from the bottom up so that when the initialization sequence;

2. When invoked, i.e., the first sequence write a second intermediate decoration is written sequentially on the intermediate, and the second on the intermediate prepared is a view sequential decorative function;

3. At the end of the call returns, the function will return to the first view of the results of a second on the intermediate prepared order, then returns to the first intermediate in the preparation of the sequence.

Code Interpretation:

@decorator1
@decorator2
def index(View):   
    pass

Guess you like

Origin www.cnblogs.com/chao666/p/12113206.html