python requests访问报403 "Invalid username/password."

使用python requests访问一个rest api时,总是报错:

403
{"detail":"Invalid username/password."}

换成curl访问就没有问题。

为什么会这样呢?

把requests的请求header print出啦,看到加了authorization,但是代码并没有使用任何认证。

{'Content-Length': '650', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'user-agent': 'a', 'Connection': 'keep-alive',  'content-type': 'application/json', 'Authorization': 'Basic dGVzdDoxMjM='}

猜测和机器环境有关系。用户认证信息应该是存在某个文件中的吧?

用strace看一下打开了哪些文件

strace python test.py

open("/usr/lib64/python2.7/shlex.py", O_RDONLY) = 4
open("/usr/lib64/python2.7/shlex.pyc", O_RDONLY) = 5
open("/root/.netrc", O_RDONLY)          = 3
open("/usr/lib64/python2.7/encodings/idna.py", O_RDONLY) = 3
open("/usr/lib64/python2.7/encodings/idna.pyc", O_RDONLY) = 4
open("/usr/lib64/python2.7/stringprep.py", O_RDONLY) = 4

访问了一个可疑文件 ~/.netrc

$ cat ~/.netrc
default login test password 123

把这个文件拿掉,接口访问就没有报错了。

查一下requests的文档,requests果然会读取.netrc文件
http://docs.python-requests.org/en/master/user/authentication/?highlight=netrc

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值