0
点赞
收藏
分享

微信扫一扫

【python】requests模块post参数data和json的区别

松鼠树屋 2022-01-11 阅读 51

requests.post主要参数是data与json,接下来看看这两者使用的主要区别

一、源码

看一下requests.post的源码:

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类型

二、参数规则

看看json与data的参数规则

2.1 json参数

  • 使用json参数,报文是dict类型
    如果不指定content-type时,默认为application/json
  • 使用json参数,报文是str类型
    如果不指定content-type时,默认为application/json

2.2 data参数

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

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

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

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

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

三、实例解析

举报

相关推荐

0 条评论