django手撸系列-实现drf框架request.data功能

一. 需求

前后端传数据三种编码格式,传json格式,原生django不能从POST中取出字典
用中间件或者装饰器前端不管传json还是其他格式,requests对象中有个data属性

二. 实现

第一步: 应用下或者项目下创建文件夹middleware

第二步: 在middleware文件夹下创建request_data.py文件

第三步: 书写代码

import json
from django.utils.deprecation import MiddlewareMixin

class RequestDataMiddle(MiddlewareMixin):

    def process_request(self, request):
        # 方法一:
        """
        if request.method == 'GET':
            request.data = dict(request.GET)

        if request.is_ajax():
            if request.method == "POST":
                try:
                    request.data = dict(json.loads(request.body))
                except Exception as e:
                    # 这里利用文件格式不能进行json格式的解码+反序列化操作实现区分是获取文件还是获取json格式的数据
                    print(e)     # 'utf-8' codec can't decode byte 0xff in position 778: invalid start byte
                    request_dict = {}
                    request_dict.update(dict(request.POST))
                    if request.FILES:
                        request_dict.update(dict(request.FILES))
                    request.data = request_dict
        """

        # 方法二:
        """
        methods = ['POST', "GET"]
        current_methods = request.method
        if current_methods in methods:
            request_method = getattr(request, current_methods)
            try:
                request.data = dict(json.loads(request.body))
            except Exception as e:
                print(e)
                request_data = {}
                request_data.update(dict(request_method))
                request_data.update(dict(request.FILES))
                request.data = request_data
        """

        # 最终精简版: 只对post和body进行区分. get请求的数据单独的通过GET或者file数据通过FILES获取即可
        try:
            request.data = json.loads(request.body)
        except Exception as e:
            print(e)
            request.data = request.POST

第四步: settings.py文件中注册刚刚熟悉的中间件

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',
    
    # 自定义注册中间价
    'app01.middleware.my_middleware.RequestDataMiddle',
]
posted @ 2020-07-07 14:53  给你加马桶唱疏通  阅读(531)  评论(0编辑  收藏  举报