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)從上述源碼中看出,參數(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)題。
- 上一篇: 删除json中为空的key-value键
- 下一篇: python之lxml处理xml