一、前言

在前端向后台发送form表单或者ajax数据的时候,django的content_type会拿到请求头中的Content-Type属性然后根据值进行解析。

将request.data中的值放到request.POST中需要满足两个条件

  • 请求头要求:

    Content-Type: application/x-www-form-urlencoded

    PS: 如果请求头中的 Content-Type: application/x-www-form-urlencoded,request.POST中才有值(去request.body中解析数据)。
  • 数据格式要求:

    name=weilan&age=18&gender=男

1、表单提交

form表单提交时会自动的将请求头中的Content-Type: application/x-www-form-urlencoded,数据也会自动转换为?parser=xxx&parser2=xxx的格式

<form action="/api/parser/" method="post">
<input type="text" name="parser"/>
<input type="text" name="parser2"/>
<input type="submit"/>
</form>>

2、ajax提交

默认的请求头中Content-Type: application/x-www-form-urlencoded

$.ajax({
url:...
type:POST,
data:{name:alex,age=18} # 内部转化 name=weilan&age=18&gender=男
})

情况一:

    $.ajax({
url:...
type:POST,
headers:{'Content-Type':"application/json"}
data:{name:weilan,age=18} # 内部转化 name=weilan&age=18&gender=男
})
# body有值;POST无

情况二:

    $.ajax({
url:...
type:POST,
headers:{'Content-Type':"application/json"}
data:JSON.stringfy({name:weilan,age=18}) # {name:weilan,age:18...} # 不在做内部转换,而是传递字符串
})
# body有值;POST无
# 这种情况下request.body有值, 需要字节类型转换成字符串类型。
# json.loads(request.body)

二、实例

1、仅处理请求头content-type为application/json的请求体

#!/usr/bin/env python
# -*- coding:utf-8 -*-
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, ] # 解析类 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请求,响应内容')

2、仅处理请求头content-type为application/x-www-form-urlencoded 的请求体

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.parsers import FormParser class TestView(APIView):
parser_classes = [FormParser, ] 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请求,响应内容') views.py

3、 仅处理请求头content-type为multipart/form-data的请求体

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.parsers import MultiPartParser class TestView(APIView):
parser_classes = [MultiPartParser, ] 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请求,响应内容')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://127.0.0.1:8000/test/" method="post" enctype="multipart/form-data">
<input type="text" name="user" />
<input type="file" name="img"> <input type="submit" value="提交"> </form>
</body>
</html> upload.html

4、仅上传文件

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.parsers import FileUploadParser class 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请求,响应内容') views.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://127.0.0.1:8000/test/f1.numbers" method="post" enctype="multipart/form-data">
<input type="text" name="user" />
<input type="file" name="img"> <input type="submit" value="提交"> </form>
</body>
</html> upload.html

6、 同时多个Parser

当同时使用多个parser时,rest framework会根据请求头content-type自动进行比对,并使用对应parser

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.parsers import JSONParser, FormParser, MultiPartParser class TestView(APIView):
parser_classes = [JSONParser, FormParser, MultiPartParser, ] 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请求,响应内容') views.py

5、全局配置

REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES':[
'rest_framework.parsers.JSONParser'
'rest_framework.parsers.FormParser'
'rest_framework.parsers.MultiPartParser'
] } settings.py

Django Rest framework 之 解析器的更多相关文章

  1. DRF Django REST framework 之 解析器(二)

    引入 Django Rest framework帮助我们实现了处理application/json协议请求的数据,如果不使用DRF,直接从 request.body 里面拿到原始的客户端请求的字节数据 ...

  2. Django Rest Framework之解析器

    基本代码结构 urls.py: from django.conf.urls import url, include from web.views.s5_parser import TestView u ...

  3. Django REST framework的解析器与渲染器

    解析器 解析器的作用 解析器的作用就是服务端接收客户端传过来的数据,把数据解析成自己可以处理的数据.本质就是对请求体中的数据进行解析. 在了解解析器之前,我们要先知道Accept以及ContentTy ...

  4. Django REST Framework - 分页 - 渲染器 - 解析器

    为什么要使用分页? 我们数据表中可能会有成千上万条数据,当我们访问某张表的所有数据时,我们不太可能需要一次把所有的数据都展示出来,因为数据量很大,对服务端的内存压力比较大还有就是网络传输过程中耗时也会 ...

  5. rest framework 之解析器

    一.示例 1.api/urls.py from django.urls import path, re_path from api.views import UserView, ParserView ...

  6. Django REST Framework的序列化器是什么?

    # 转载请留言联系 用Django开发RESTful风格的API存在着很多重复的步骤.详细可见:https://www.cnblogs.com/chichung/p/9933861.html 过程往往 ...

  7. django rest framework 自定义验证器

    一.基于钩子函数: 官网上的例子: 官方提示:如果字段声明在序列化类上时,就具有参数required=Fasle的作用,当函数名中没有包括字段名时,那么这个验证函数就不起作用 二.基于类的验证器: 使 ...

  8. Django Rest framework 之 序列化

    RESTful 规范 django rest framework 之 认证(一) django rest framework 之 权限(二) django rest framework 之 节流(三) ...

  9. Django Rest framework 之 版本

    RESTful 规范 django rest framework 之 认证(一) django rest framework 之 权限(二) django rest framework 之 节流(三) ...

随机推荐

  1. Avro实现RPC

    场景:一个客户端,一个服务端(创建两个avro工程).客户端向服务端发送数据,服务端根据算法算出结果,返回给客户端. Http主外,RPC主内.(解决分布式环境下,节点间的数据通信或远程过程调用) 实 ...

  2. bash编程-sed

    sed(Stream Editor)是Linux系统下的一个文本流编辑器,它将文本文件内容逐行读取到标准输出,并将此行内容写入模式空间(pattern space),然后按照给定的地址定界和命令处理匹 ...

  3. iOS 抓包

    通过tcpdump对iOS进行流量分析(无需越狱 iOS Packet Tracing 将 iOS 设备通过 USB 连接到 Mac 打开 terminal rvictl -s $UDID 运行 tc ...

  4. getaddrinfo 报错 Invalid value for ai_flags

    最近改了游戏的网络层代码,运行 Android 版的时候 getaddrinfo 报错 Invalid value for ai_flags. ai_flags 设置如下: struct addrin ...

  5. SpringBoot swagger-ui.html 配置类继承 WebMvcConfigurationSupport 类后 请求404

    1 .SpringBoot启动类加上  注解 @EnableWebMvc @SpringBootApplication@EnableWebMvc public class Application { ...

  6. ElasticSearch权威指南学习(排序)

    排序方式 相关性排序 默认情况下,结果集会按照相关性进行排序 -- 相关性越高,排名越靠前. 相关性分值会用_score字段来给出一个浮点型的数值,所以默认情况下,结果集以_score进行倒序排列. ...

  7. postgres Date/Time 学习笔记

    一.Date/Time Types 参考文档:https://www.postgresql.org/docs/9.2/static/datatype-datetime.html Types 别名 ti ...

  8. Python总纲路线

    比较全面的Python学习方案: 一,Python 基础教程 二,Python 高级教程 这是系统写学习资料参考,后面会整理单个的学习应用内容. 廖雪峰Python教程传送门

  9. Shell - 文本处理

    珠玉在前,不再赘言. 常用命令 LinuxShell文本处理工具集锦 数据工程师常用的Shell命令 文件和目录管理 简明教程 AWK简明教程 SED简明教程 命令详解 linux sort,uniq ...

  10. python tricks

    1. cities = ['Marseille', 'Amsterdam', 'New York', 'Londom'] # the good way for i, city in enumerate ...