Python-Requests.post方法中,传参data与json的区别

Python3的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 (will be form-encoded), 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)

从上述源码中看出,参数中明确的参数是data和json
datajson2个参数,类型既可以是str,也可以是dict
区别如下:

  • 不管jsonstr还是dict,如果不指定headers中的content-type,默认为application/json
  • data参数dict时,如果不指定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())得到想要的值
  • data参数str时,如果不指定content-type,默认为application/json
  • 用data参数提交数据时,request.body的内容则为a=1&b=2的这种形式,用json参数提交数据时,request.body的内容则为'{"a": 1, "b": 2}'的这种形式

因此,拿注册接口来说明,有两种实现方式:

 

 

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Python,可以使用`requests.post`方法来发送POST请求。有几种不同的用法可以根据你的需求选择。 第一种方式是使用`x-www-form-urlencoded`格式的数据发送POST请求。你可以使用一个字典来表示要发送的数据,然后将该字典作为`data`递给`requests.post`方法。例如: ```python import requests url = "https://editor.net/" data = {"key": "value"} # 字典格式,外层无引号 resp = requests.post(url, data=data) print(resp.text) ``` 第二种方式是使用Python模拟浏览器发送POST请求。你可以使用`requests.post`方法,并通过`data`递要发送的数据。与第一种方式不同的是,该数可以接受字符串作为输入。例如: ```python import requests url = "https://editor.net/" data = '{"key": "value"}' # 字符串格式 resp = requests.post(url, data=data) print(resp.text) ``` 除了上述两种方式,还可以使用`json`数来发送POST请求。你可以将要发送的数据转换为JSON格式的字符串,并将其作为`data`递给`requests.post`方法。例如: ```python import requests url = "https://editor.net/" data = {"key": "value"} # 字典格式 resp = requests.post(url, json=data) print(resp.text) ``` 以上就是Python`requests.post`方法的用法。你可以根据不同的需求选择适合的方式来发送POST请求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [python requests post 使用方法](https://blog.csdn.net/qq_42777433/article/details/105829795)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值