Django middleware incorporates the use of Vue interceptors

  • 2021-11-29 07:30:17
  • OfStack

What is the directory axios interceptor? Use of interceptors Request interceptor
Response interceptor
Django Middleware token Verification Middleware correlation
Custom middleware
Execution flow of middleware
Login authentication with middleware
Summarize

What is an axios interceptor?

The axios interceptor can intercept every request and response, and then process it accordingly. Interceptors are divided into request interceptors and response interceptors. Request interceptors can add token to the request body before you send the request; If you respond to the interceptor, it is one operation after receiving the response. For example, when the server returns to the login status and needs to log in again, it will jump to the login page;

Use of interceptors

I like global configuration as much as I do (main. js)

Request interceptor


//  interceptors
axios.interceptors.request.use(
  config => {
 //  Object for login success status maintenance token
    let token = localStorage.getItem('token')
 //  If there is token Just add it to the head token
    if (token) {
      config.headers['Authorization'] = token
    }
    return config
  },
  error => {
 //  If not token Returns the error message 
    return Promise.reject(error.response);
  });

Response interceptor


axios.interceptors.response.use(function (response) {
    //  What to do when receiving the response, such as jumping to the login page 
    ......
    return response;
  }, function (error) {
    //  Do something about response errors 
    return Promise.reject(error);
  });

Interceptor is super easy to use ~ ~ ~

Django Middleware token Verification

Middleware correlation

Middleware is a framework-level hook for processing Django requests and responses. It is a lightweight, low-level plug-in system for changing the input and output of Django globally. Each middleware component is responsible for doing 1 specific function. However, because it affects the whole situation, it needs to be used carefully, and improper use will affect performance. To put it bluntly, middleware helps us to do some extra operations before and after the execution of view functions. It is essentially a custom class with several methods defined in the class, and the Django framework will execute these methods at a specific time requested.

Custom middleware

Middleware can define five methods, which are: (mainly process_request and process_response)

process_request(self,request) process_view(self, request, view_func, view_args, view_kwargs) process_template_response(self,request,response) process_exception(self, request, exception) process_response(self, request, response)

The return value of the above method can be None or an HttpResponse object. If it is None, the execution will continue according to the rules defined by django. If it is HttpResponse object, the object will be directly returned to the user.

Execution flow of middleware

After the request arrives at the middleware, the process_reques method of each registered middleware is executed in positive order. If the value returned by the process_request method is None, it is executed in turn. If the returned value is HttpResponse object, the following process_request method is no longer executed, but the process_response method of the current corresponding middleware is executed. The HttpResponse object is returned to the browser. That is to say, if six middleware are registered in MIDDLEWARE, and the third middleware returns one HttpResponse object during execution, the process_request and process_response methods of middleware 4, 5 and 6 are not executed, and the process_response methods of middleware 3, 2 and 1 are executed sequentially.

Login authentication with middleware

Code on tactical drinking water ~ ~


# Author : Carl
# Date :2021/8/27 9:43
# File :tokenMiddleware.py

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

import jwt

from meiduo import settings


class TokenMiddleware(MiddlewareMixin):
    """
     Middleware generation Token
    """

    def process_request(self, request):
        """
        token Certification 
        :param request:
        :return:token
        """
        #  Get url
        url = request.get_full_path()
        #  Definition 1 White list   Register login interface   Visit casually 
        white_list = ['/sadmin/login/','/admin/']
        #  Judge url Is not in the white list 
        if url not in white_list:
            #  Get token jwttoken Certification to certification 
            token = request.META.get('HTTP_AUTHORIZATION')
            #  Analytic validation 
            if token:
                #  Solve the original token
                old_token = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
                #  Regeneration token
                new_token = str(jwt.encode(old_token, settings.SECRET_KEY, algorithm='HS256'), encoding='utf8')
                if token == new_token:
                    return None
            return HttpResponse('401')
        return None
 

Summarize

When an interface is requested, If the user is not logged in, Is released when the request reaches the middleware, Add the view layer, match the password mobile phone number, user name, password, etc. in the view layer. After the matching is successful, return the generated token to the front end for state maintenance. Use the interceptor to add token (token for state maintenance) at the head of each request, and analyze and compare token by middleware. If the comparison is successful, enter the view layer; Otherwise, return 401 (without authority).


Related articles: