Before we get to that, let’s take a look at the main formats in which the front end passes parameters
POST request:1.Content-type: application/json or text/plain or text/ XML The parameters are in: request.body2.Form-data Form data, with parameters in request.POST3.X-www-form-urlencoded, parameters in: request.postCopy the code
From this we know that the parameters we need to fetch are either in Request.body or request.post, so we just need to use a middleware to process the data so that we can fetch the data directly regardless of the front-end request format
Write middleware to process the data requested by the front end
Step 1: Write middleware
from django.utils.deprecation import MiddlewareMixin
import json
class RequestMiddlewareMixin(MiddlewareMixin) :
def process_request(self, request) :
Consolidates the different request modes of the POST request into request.data.
if request.method == 'POST':
try:
request.data = json.loads(request.body)
except Exception as e:
request.data = request.POST
Copy the code
Step 2: Register middleware
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'.'apps.user.CustomMiddlewareMixin.RequestMiddlewareMixin' Add middleware to the middleware list
]
Copy the code
Pay attention to the point
Registered middleware package under the best guide to avoid middleware path error, the following guide pieced together before and after the package path is the path of the middleware from apps. User. CustomMiddlewareMixin import RequestMiddlewareMixin