gpt4 book ai didi

python - 在 Python 中使用 'requests' 模块发出 POST 请求

转载 作者:太空宇宙 更新时间:2023-11-04 01:20:36 25 4
gpt4 key购买 nike

所以我已经安装了 python 的“请求”模块,它可以正常工作,但我无法理解它们是如何组合在一起的。我在网上搜索过,但找不到任何实际的例子来说明它是如何工作的。

因此,我将提供一个示例 POST 请求,而我正在寻找的答案是 Python 代码中的请求。我到处都看过,但我找不到任何直接转换基本 POST 格式和它在 Python 中的外观之间的关系。

感谢您的帮助!

这是我的 POST 请求示例:

POST / HTTP/1.1
content-type:application/x-www-form-urlencoded;charset=utf-8
host: https://testsite.com
content-length:207

Blah=content&blah2=content2

最佳答案

使用 .post() 函数将字典传递给 data 关键字:

data = {'Blah': 'content', 'blah2': 'content2'}
r = requests.post('https://testsite.com/', data=data)

参见 More complicated POST requests快速入门文档的一部分。

同一篇文章http://httpbin.org/post :

>>> import requests, pprint
>>> data = {'Blah': 'content', 'blah2': 'content2'}
>>> r = requests.post('http://httpbin.org/post', data=data)
>>> pprint.pprint(r.json())
{u'args': {},
u'data': u'',
u'files': {},
u'form': {u'Blah': u'content', u'blah2': u'content2'},
u'headers': {u'Accept': u'*/*',
u'Accept-Encoding': u'gzip, deflate, compress',
u'Connection': u'close',
u'Content-Length': u'27',
u'Content-Type': u'application/x-www-form-urlencoded',
u'Host': u'httpbin.org',
u'User-Agent': u'python-requests/2.0.1 CPython/2.7.5 Darwin/11.4.2',
u'X-Request-Id': u'6df0a100-f193-4272-adf5-3b6bb6a77461'},
u'json': None,
u'origin': u'84.92.98.170',
u'url': u'http://httpbin.org/post'}
>>> r.request.headers
CaseInsensitiveDict({'Content-Length': u'27', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept-Encoding': 'gzip, deflate, compress', 'Accept': '*/*', 'User-Agent': 'python-requests/2.0.1 CPython/2.7.5 Darwin/11.4.2'})

httpbin.org 回显已发送的 header ; Content-LengthContent-Type header 由 requests 设置。

您始终可以使用 headers 参数添加或覆盖 header :

>>> r = requests.post('http://httpbin.org/post', data=data,
... headers={'User-Agent': 'Stack Overflow requests demo'})
>>> pprint.pprint(r.json())
{u'args': {},
u'data': u'',
u'files': {},
u'form': {u'Blah': u'content', u'blah2': u'content2'},
u'headers': {u'Accept': u'*/*',
u'Accept-Encoding': u'gzip, deflate, compress',
u'Connection': u'close',
u'Content-Length': u'27',
u'Content-Type': u'application/x-www-form-urlencoded',
u'Host': u'httpbin.org',
u'User-Agent': u'Stack Overflow requests demo',
u'X-Request-Id': u'b489f151-e5c2-4f49-ad00-141a0658c54a'},
u'json': None,
u'origin': u'84.92.98.170',
u'url': u'http://httpbin.org/post'}
>>> r.request.headers
CaseInsensitiveDict({'Content-Length': u'27', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept-Encoding': 'gzip, deflate, compress', 'Accept': '*/*', 'User-Agent': 'Stack Overflow requests demo'})

关于python - 在 Python 中使用 'requests' 模块发出 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21505716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com