zoukankan      html  css  js  c++  java
  • 【1119 | Day62】drf之解析模块

    一、解析模块

    根据请求头content-type选择对应的解析器对请求体内容进行处理,如:application/json,x-www-form-urlencoded,form-data等格式

    二、局部解析

    局部配置:

    可以在视图类中通过parser_classes类属性对该视图的数据包解析做配置。

    例如:

    #api/urls.py
    
    from django.conf.urls import url, include
    from web.views.s5_parser import TestView
    
    urlpatterns = [
     url(r'test/', TestView.as_view(), name='test'),
    ]
    
    #api/views.py
    
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework.request import Request
    from rest_framework.parsers import JSONParser
    
    class TestView(APIView):
     	parser_classes = [JSONParser, ] #仅处理请求头content-type为application/json的请求体
       #parser_classes = [FormParser, ] #仅处理请求头content-type为application/x-www-form-urlencoded 的请求体
       #parser_classes = [MultiPartParser, ] #仅处理请求头content-type为multipart/form-data的请求体
       
     	def post(self, request, *args, **kwargs):
     		print(request.content_type)
     		# 获取请求的值,并使用对应的JSONParser进行处理
     		print(request.data)
     
     		# application/x-www-form-urlencoded 或 multipart/form-data时,request.POST中才有值
     		print(request.POST)
     		print(request.FILES)
     		
     		return Response('POST请求,响应内容')
     
     	def put(self, request, *args, **kwargs):
     		return Response('PUT请求,响应内容')
    

    三、全局解析

    全局配置:

    可以在项目的配置文件的drf配置中通过DEFAULT_PARSER_CLASSES对该视图的数据包解析做配置。

    例如:

    #settings.py配置
    
    REST_FRAMEWORK = {
     	'DEFAULT_PARSER_CLASSES':[
             'rest_framework.parsers.JSONParser'
             'rest_framework.parsers.FormParser'
             'rest_framework.parsers.MultiPartParser'
     	]
    }
    
    #urls.py配置
    
    urlpatterns = [
     	url(r'test/', TestView.as_view()),
    ]
    
    #视图函数
    
    from rest_framework.views import APIView
    from rest_framework.response import Response
    
    class TestView(APIView):
     	def post(self, request, *args, **kwargs):
     		print(request.content_type)
    
            # 获取请求的值,并使用对应的JSONParser进行处理
             print(request.data)
             
             # application/x-www-form-urlencoded 或 multipart/form-data时,request.POST中才有值
             print(request.POST)
             print(request.FILES)
             return Response('POST请求,响应内容')
             
        def put(self, request, *args, **kwargs):
             return Response('PUT请求,响应内容')
    

    核心:

    请求的数据包格式会有三种(json、urlencoded、form-data),drf默认支持三种数据的解析,可以全局或局部配置视图类具体支持的解析方式。

  • 相关阅读:
    diary and html 文本颜色编辑,行距和其它编辑总汇
    bash coding to changeNames
    virtualbox ubuntu 网络连接 以及 连接 secureCRT
    linux 学习6 软件包安装
    linux 学习8 权限管理
    vim 使用2 转载 为了打开方便
    ubuntu
    linux 学习15 16 启动管理,备份和恢复
    linux 学习 14 日志管理
    linux 学习 13 系统管理
  • 原文地址:https://www.cnblogs.com/fxyadela/p/11892238.html
Copyright © 2011-2022 走看看