对应 请求头的content_type选择对应的解析器对应的请求体内容进行处理
有application/json、x-www-form-urlencoded、form-data等格式
1、settiing文件中
REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES':[ 'rest_framework.parsers.JSONParser' 'rest_framework.parsers.FormParser' 'rest_framework.parsers.MultiPartParser' ]}
2、路由层
urlpatterns = [ url(r'test/', TestView.as_view()),]
3、视图层中
from rest_framework.views import APIViewfrom rest_framework.response import Responseclass 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请求,响应内容')
1、仅处理请求头content-type为application/json的请求体
from django.conf.urls import url, includefrom web.views.s5_parser import TestViewurlpatterns = [ url(r'test/', TestView.as_view(), name='test'),]
from rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework.request import Requestfrom rest_framework.parsers import JSONParserclass TestView(APIView): parser_classes = [JSONParser, ] 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请求,响应内容')
2、仅上传文件
from django.conf.urls import url, includefrom web.views import TestViewurlpatterns = [ url(r'test/(?P<filename>[^/] )', TestView.as_view(), name='test'),]
#!/usr/bin/env python# -*- coding:utf-8 -*-from rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework.request import Requestfrom rest_framework.parsers import FileUploadParserclass TestView(APIView): parser_classes = [FileUploadParser, ] def post(self, request, filename, *args, **kwargs): print(filename) 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请求,响应内容')
1、通过reques.data 进行解析,由此入手
2、通过查看self._load_data_and_files()方法---->self._data, self._files = self._parse()
3、查看_parse
4、查看self.negotiator.select_parser(self, self.parsers)
5、最终调用parser的解析方法来解析parsed = parser.parse(stream, media_type, self.parser_context)来源:https://www.icode9.com/content-4-305351.html
联系客服