requests.post方法中data与json参数区别

zz:https://blog.csdn.net/liudinglong1989/article/details/104604626

目录

  引言

  Requests参数

  实例解析

  总结


  引言

  在随笔分类Jmeter入门基础中,分享过一篇《Jmeter处理http请求Content-Type类型和传参方式》,这篇文章主要讲述Jmeter做接口测试时,针对POST请求参数的传递方式。而在使用requests做接口测试的时候,与之不太一样。requests.post主要参数是data与json,这两者使用是有区别的,下面我详情的介绍一下使用方法。

  Requests参数

1. 先可以看一下requests的源码:


     
     
  1. def post(url, data=None, json=None, **kwargs):
  2. r"""Sends a POST request.
  3. :param url: URL for the new :class:`Request` object.
  4. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  5. object to send in the body of the :class:`Request`.
  6. :param json: (optional) json data to send in the body of the :class:`Request`.
  7. :param \*\*kwargs: Optional arguments that ``request`` takes.
  8. :return: :class:`Response <Response>` object
  9. :rtype: requests.Response
  10. """
  11. return request('post', url, data=data, json=json, **kwargs)

 

说明:

  从源码中注释看,告诉我们post请求报文中既可以传data,也可以传json。并且data与json,既可以是str类型,也可以是dict类型。

 

2. json与data参数规则:

一、JSON

1.使用json参数,不管报文是str类型,还是dict类型,如果不指定headers中content-type的类型,默认是:application/json。

二、DATA

1.使用data参数,报文是dict类型,如果不指定headers中content-type的类型,默认application/x-www-form-urlencoded,相当于普通form表单提交的形式,会将表单内的数据转换成键值对,此时数据可以从request.POST里面获取,而request.body的内容则为a=1&b=2的这种键值对形式。

注意:即使指定content-type=application/json,request.body的值也是类似于a=1&b=2,所以并不能用json.loads(request.body.decode())得到想要的值。

2. 使用data参数,报文是str类型,如果不指定headers中content-type的类型,默认application/json。
 

综上所述,两种参数的使用情况:

用data参数提交数据时,request.body的内容则为a=1&b=2的这种形式,用json参数提交数据时,request.body的内容则为'{"a": 1, "b": 2}'的这种形式

 

  实例解析

  知道了上面所讲的理论,需要通过实例来验证一下。

以我django项目开发的web接口为例:

url.py文件


     
     
  1. from django.contrib import admin
  2. from django.urls import path,include
  3. from django_web.views import views
  4. from django.conf.urls import url
  5. urlpatterns = [
  6. path('admin/', admin.site.urls),
  7. #首页
  8. path('index/',views.test_dj), #登陆页面

view.py文件


     
     
  1. def test_dj(request):
  2. print(request.body,111)
  3. print(request.headers)
  4.   
  5. """
  6. 当post请求的请求体以data为参数,发送过来的数据格式为:b'username=test&password=123'
  7. 当post请求的请求体以json为参数,发送过来的数据格式为:b'{"username": "test", "password": "123"}'
  8. """
  9. return render(request, 'index.html')

  

exp1:

test.py


     
     
  1. import requests
  2. headers = {'content-type':'application/json'}
  3. data = {
  4. "username": "test",
  5. "password": "123"
  6. }
  7. print(type(data)) #dict
  8. r1 = requests.post(url="http://127.0.0.1:8000/index/",data=data)
  9. print(r1.text)

 

返回的报文:


     
     
  1. b'username=test&password=123' 111
  2. {'Content-Length': '26', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': '127.0.0.1:8000', 'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}

 

exp1案例:证实了第二条规则:使用data参数,报文是dict类型,不指定content-type,默认是:application/x-www-form-urlencoded,请求数据格式是:key1=value1&key2=value2键值对形式。

 

exp2:

test.py


     
     
  1. import requests
  2. headers = {'content-type':'application/json'}
  3. data = {
  4. "username": "test",
  5. "password": "123"
  6. }
  7. print(type(data)) #dict
  8. r1 = requests.post(url="http://127.0.0.1:8000/index/",json=data)
  9. print(r1.text)

 

将参数data换成json请求,返回的报文:


     
     
  1. b'{"username": "test", "password": "123"}' 111
  2. {'Content-Length': '39', 'Content-Type': 'application/json', 'Host': '127.0.0.1:8000', 'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}

exp2案例:证实了第一条规则:使用json参数,报文是dict类型,如果不指定headers中content-type的类型,默认是:application/json,请求数据格式是:dict形式。

 

exp3:

test.py


     
     
  1. import requests,json
  2. headers = {'content-type':'application/json'}
  3. data = {
  4. "username": "test",
  5. "password": "123"
  6. }
  7. print(type(data)) #dict
  8. # 方法1
  9. r1 = requests.post(url="http://127.0.0.1:8000/index/",data=json.dumps(data))
  10. # 方法2
  11. r2 = requests.post(url="http://127.0.0.1:8000/index/",json=json.dumps(data))
  12. print(r1.text)
  13. print(r2.request)

 

查看返回报文:


     
     
  1. b'{"username": "test", "password": "123"}' 111
  2. {'Content-Length': '39', 'Content-Type': 'text/plain', 'Host': '127.0.0.1:8000', 'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
  3. b'"{\\"username\\": \\"test\\", \\"password\\": \\"123\\"}"' 111
  4. {'Content-Length': '49', 'Content-Type': 'application/json', 'Host': '127.0.0.1:8000', 'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
  5. [01/Mar/2020 14:02:11] "POST /index/ HTTP/1.1" 200 1890

  

exp3案例

证实了第一条规则:使用json参数,报文是str类型,如果不指定headers中content-type的类型,默认是:application/json,请求数据格式是:dict形式。也就是test.py中的方法2.

还证实了第三条规则:使用data参数,报文是str类型,如果不指定headers中content-type的类型,默认application/json。其实方法1和方法2是等价的。报文是json字符串数据,分别以data与json两种参数形式发送请求,得到的请求体数据格式是一样。

 

注意:方法1返回的数据类型是:'Content-Type': 'text/plain',表示无格式,但规则说是默认application/json,是否有冲突? 其实不然,服务器并没有强制指定接收数据的格式类型,所以这种情况下也不会报错。

 

 

 

  总结

  总而言之,记住这句话:用data参数提交数据时,request.body的内容则为a=1&b=2的这种形式,用json参数提交数据时,request.body的内容则为'{"a": 1, "b": 2}'的这种形式。

 

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值