• rest-framework之解析器


    1、解析器的作用

    根据请求头 content-type 选择对应的解析器对请求体内容进行处理;

    有application/json,x-www-form-urlencoded,form-data等格式;


    举例说明:

    1)发送application/json数据,让后端接收:
    views.py

    from django.shortcuts import render
    from rest_framework.views import  APIView
    from rest_framework.response import  Response
    
    class Test(APIView):
        def post(self, request):
            print(request.data)
            print(type(request.data))
            return Response()


    urls.py

    url(r'^test/', views.Test.as_view()),


    postman测试,后端接收的是一个字典:

    image

    image


    2)发送x-www-form-urlencoded数据,让后端接收:

    视图和路由都不变;


    postman测试,后端接收的是一个QueryDict:

    image

    image


    3)发送form-data数据,让后端接收:

    后端接收的也是一个QueryDict,不截图了;


    由此可见:默认可以解析以上三种格式;



    2、解析器的使用

    现在问题来了,如果我只想解析application/json格式的数据怎么办呢?

    1)解析器的局部使用

    views.py

    from django.shortcuts import render
    from rest_framework.views import  APIView
    from rest_framework.response import  Response
    
    # 导入模块
    from rest_framework.parsers import JSONParser
    
    
    class Test(APIView):
        parser_classes = [JSONParser,]  # 只解析application/json
        def post(self, request):
            print(request.data)
            print(type(request.data))
            return Response()


    其他配置不变,测试一下,可见其他格式已经不行了,就不逐一测试了:

    image


    2)解析器的全局使用

    setttins.py

    REST_FRAMEWORK = {
        'DEFAULT_PARSER_CLASSES':[
            'rest_framework.parsers.JSONParser'
            'rest_framework.parsers.FormParser'
            'rest_framework.parsers.MultiPartParser'
        ]
    }
  • 相关阅读:
    clickhouse-(04)-常用高阶函数
    clickhouse-(03)-库和表引擎
    clickhouse-(02)-适合的场景
    clickhouse-(01)-安装
    MySQL实战45讲-笔记
    Linux软连接和硬链接
    直接访问和间接访问
    指针和地址的区别
    配置Apache 运行CGI---------笔记
    配置Apache 运行CGI
  • 原文地址:https://www.cnblogs.com/weiyiming007/p/12522760.html
Copyright © 2020-2023  润新知