Django rest-framework框架-解析器

解析器:

开始: django: request.POST/ request.body
    满足一下两个要求POST中才有值
    1. 如果请求头中的 Content-Type: application/x-www-form-urlencodeed, request.POST 中才有值(request.body中解析数据)
    2. 数据格式要求:
        name-alex$age=18$gender=x
    如: 
     a. form表单提交
         <form>
         	....
         	....
         </form>
      b. ajax提交
          # request.POST无值,request.body有值
          $.ajax{(
          	url: ...,
          	type: POST,
          	headers: {'Content-Type': 'application/json'},
          	data: {name:x,age=10},
          )}

rest_framework的解析器:

from rest_framework.parsers import JSONParser,FormParser

#允许用户发送json格式数据 content-type: application/json
#                       {"name":"alex","age":10}
class TestView(APIView):
      #JSONParser 表示只能解析content-type;application/json头
      #FormParser 表示只能解析content-type;application/x-www-form-urlencoded头
      parser_classes = [JSONParser,FormParser,]
      def post(self,request,*args,**kwargs):
      	  return request.data

全局配置:
"DEFAULT_PARSER_CLASSES": ["rest_framework.parsers.JSONParser", "rest_framework.parsers.FormParser"]
   
解析器使用就做上全局配置就可以了

  

猜你喜欢

转载自www.cnblogs.com/kuku0223/p/11346399.html