gpt4 book ai didi

python - 使用 Python 请求进行 Rest API 身份验证和访问

转载 作者:太空宇宙 更新时间:2023-11-03 17:49:59 24 4
gpt4 key购买 nike

我在工作中经常使用curl 访问API。但现在我需要做一些自动化。试图使用 requests 模块将我对curl所做的事情翻译成python。但我不断收到 401 错误。

我经常提出的curl请求如下:

第 1 步:使用 cookie 进行 session 身份验证:

curl -b cookies -c cookies -v -X POST -H "Content-Type: application/json" --data-binary '{"auth":{"username":"aaa","password":"bbb"}}' http://api.xyz.at/auth

第2步:访问API URL以检索数据

curl -b cookies -c cookies http://api.xyz.at/somepage?per_id=556677

现在使用 Python 请求,这就是我正在做的事情

第1步:进行身份验证

username = 'aaa'
password = 'bbb'
s = requests.Session()
s.post('http://api.xyz.at/auth',auth=('username','pasword'))

这个“我认为”效果很好,请给我以下回复

<Response [200]>

第2步:访问API URL以检索数据

s.get('http://api.xyz.at/somepage?per_id=556677')

但是第 2 步不断返回错误

<Response [401]>

代码失败并且不确定哪里。

我的 Python 技能显然很平淡。我一直在查看请求网站。但遗憾的是一直没能破译。指导将不胜感激:)

最佳答案

import urllib2, urllib
url = 'http://api.xyz.at/auth'
pm = urllib2.HTTPPasswordMgrWithDefaultRealm()
pm.add_password(None, url, 'user', 'password')
auth = urllib2.HTTPBasicAuthHandler(pm)
opener = urllib2.build_opener(auth)
urllib2.install_opener(opener)
request = urllib2.Request('http://api.xyz.at/somepage?per_id=556677', None)
handler = urllib2.urlopen(request)
handler.read()

关于python - 使用 Python 请求进行 Rest API 身份验证和访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29250659/

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