zoukankan      html  css  js  c++  java
  • Python 接口测试requests.post方法中data与json参数区别

      引言

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

      Requests参数

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

    def post(url, data=None, json=None, **kwargs):
        r"""Sends a POST request.
    
        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary, list of tuples, bytes, or file-like
            object to send in the body of the :class:`Request`.
        :param json: (optional) json data to send in the body of the :class:`Request`.
        :param **kwargs: Optional arguments that ``request`` takes.
        :return: :class:`Response <Response>` object
        :rtype: requests.Response
        """
    
        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文件

    from django.contrib import admin
    from django.urls import path,include
    from django_web.views import views
    from django.conf.urls import url
    
    urlpatterns = [
        path('admin/', admin.site.urls),
    
        #首页
        path('index/',views.test_dj), #登陆页面
    

    view.py文件

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

      

    exp1:

    test.py

    import requests
    
    headers = {'content-type':'application/json'}
    
    data = {
        "username": "test",
    
        "password": "123"
    }
    
    print(type(data)) #dict
    r1 = requests.post(url="http://127.0.0.1:8000/index/",data=data)
    
    
    print(r1.text)

    返回的报文:

    b'username=test&password=123' 111
    {'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

    import requests
    
    headers = {'content-type':'application/json'}
    
    data = {
        "username": "test",
    
        "password": "123"
    }
    
    print(type(data)) #dict
    r1 = requests.post(url="http://127.0.0.1:8000/index/",json=data)
    
    
    print(r1.text)
    

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

    b'{"username": "test", "password": "123"}' 111
    {'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

    import requests,json
    
    headers = {'content-type':'application/json'}
    
    data = {
        "username": "test",
    
        "password": "123"
    }
    
    print(type(data)) #dict
    
    # 方法1
    r1 = requests.post(url="http://127.0.0.1:8000/index/",data=json.dumps(data))
    # 方法2
    r2 = requests.post(url="http://127.0.0.1:8000/index/",json=json.dumps(data))
    
    
    print(r1.text)
    print(r2.request)
    

    查看返回报文:

    b'{"username": "test", "password": "123"}' 111
    {'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'}
    b'"{\"username\": \"test\", \"password\": \"123\"}"' 111
    {'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'}
    [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}'的这种形式。

    如果觉得此文对您有帮助,请给个赞以示鼓励,谢谢。

  • 相关阅读:
    XOR加密作业
    2019-2020-1 20191312《信息安全专业导论》第六周学习总结
    欧几里得算法及其伪代码
    2019-2020-1 20191312《信息安全专业导论》第五周学习总结
    2019-2020-1 20191312《信息安全专业导论》第四周学习总结
    寻找你的黑客偶像作业
    2019-2020-1 20191312 《信息安全专业导论》第三周学习总结
    罗马数字转化为阿拉伯数字
    IEEE754 浮点数
    2019-2020-2 网络对抗技术 20175211 Exp6 MFS基础应用
  • 原文地址:https://www.cnblogs.com/liudinglong/p/12389650.html
Copyright © 2011-2022 走看看