日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

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

發(fā)布時(shí)間:2025/3/20 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python-Requests.post方法中,传参data与json的区别 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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)

從上述源碼中看出,參數(shù)中明確的參數(shù)是data和json
data與json2個(gè)參數(shù),類型既可以是str,也可以是dict
區(qū)別如下:

不管json是str還是dict,如果不指定headers中的content-type,默認(rèn)為application/json
data參數(shù)為dict時(shí),如果不指定content-type,默認(rèn)為application/x-www-form-urlencoded,相當(dāng)于普通form表單提交的形式,此時(shí)數(shù)據(jù)可以從request.POST里面獲取,而request.body的內(nèi)容則為a=1&b=2的這種形式,注意,即使指定content-type=application/json,request.body的值也是類似于a=1&b=2,所以并不能用json.loads(request.body.decode())得到想要的值
data參數(shù)為str時(shí),如果不指定content-type,默認(rèn)為application/json
用data參數(shù)提交數(shù)據(jù)時(shí),request.body的內(nèi)容則為a=1&b=2的這種形式,用json參數(shù)提交數(shù)據(jù)時(shí),request.body的內(nèi)容則為’{“a”: 1, “b”: 2}'的這種形式
因此,拿注冊(cè)接口來(lái)說(shuō)明,有兩種實(shí)現(xiàn)方式:

總結(jié)

以上是生活随笔為你收集整理的Python-Requests.post方法中,传参data与json的区别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。