- 根据请求头 content-type 选择对应的解析器就请求体内容进行处理。
1.request.POST中有值的前提:
- 请求头要求:如果请求头中的Content-Type:application/x-www-form-urlencoded,request.POST中有值(去request.body中解析数据)
- 数据格式要求: name=alex&age=18&gender-=男 (不论是ajax或者是表单提交 内部都会转换成这种格式)
2.全局配置
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': ['rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser']
}
3.代码部分
- MultiPartParser 'multipart/form-data'
- JSONParser 'application/json'
- FormParser 'application/x-www-form-urlencoded'
- FileUploadParser 上传文件的时候的解析器
from rest_framework.parsers import JSONParser, FormParser
class DjangoView(APIView):
parser_classes = [JSONParser, FormParser] #比如只写入 JSONParser 表示只能解析content-type: application/json FormParser 只能解析 content-type: application/x-www-urlencoded
def post(self, request, *args, **kwargs):
'''
1.用户请求
2.获取用户请求体
3.获取用户请求头 和 parser_classes=[JSONParser,FormParser,] 中支持的请求头进行比较
4.根据对应的解析器去解析对应的方法
5.解析后的数据封装到request.data
'''
print(request.data)