zoukankan      html  css  js  c++  java
  • 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'
        ]
    }
  • 相关阅读:
    从服务器上下载下来的代码,部署到本地时,Url自动带www前缀
    个人说明
    名词解释
    Bandizip-解压缩软件
    uTools-工具插件集
    Geek-软件卸载工具
    Microsoft商店软件推荐
    Docker入门第九章
    Docker入门第八章
    IDM-下载工具
  • 原文地址:https://www.cnblogs.com/weiyiming007/p/12522760.html
Copyright © 2011-2022 走看看