【问题标题】:Converting CURL Command to Python 2.7将 CURL 命令转换为 Python 2.7
【发布时间】:2017-10-22 06:44:17
【问题描述】:

我有一个 curl 命令,它运行得非常好,并且给了我一个 HTTP 200。

curl -i -H "Authorization: Basic jadkfhjkafDSKJ12DD=" http://<ip>/LoadTest/rest/authentication-point/authenticate

以上API需要base64格式的授权,详细信息必须作为Headers传递。这是一个 GET 请求。

当我尝试在 Python 2.7 中运行相同的程序时,我得到了Response [403]。代码如下。

import requests
headers = {'Authorization': 'Basic jadkfhjkafDSKJ12DD='}
authurl = "http://<ip>/LoadTest/rest/authentication-point/authenticate"
r = requests.get(authurl, headers=headers)
print r.status_code

我在这里缺少什么?我应该如何像在 curl 命令中传递的一样传递授权值?我尝试了多种方法,但最终还是总是得到 HTTP 403。请指导。

【问题讨论】:

  • 解决此问题的最简单方法不是捕获网络流量并查看您的通话有何不同吗?
  • 当然,我该怎么做?请建议
  • 你试过用谷歌吗?
  • 可能是以下陷阱之一(来自docs.python-requests.org/en/master/user/quickstart): 1. 如果在 .netrc 中指定了凭据,则使用 headers= 设置的授权标头将被覆盖,而 auth= 又将被覆盖范围。 2. 如果您被重定向到主机外,授权标头将被删除。
  • 感谢蒂姆的投入。在我做了一些更改并添加 session = requests.Session() session.trust_env = False 后,我现在得到 HTTP 500

标签: python curl base64 python-requests


【解决方案1】:

感谢大家的投入。这是最终的解决方案。我发现有代理正在停止有效负载。因此将会话添加到请求中。

import requests
session = requests.Session()
session.trust_env = False
headers = {'Authorization': 'Basic jadkfhjkafDSKJ12DD='}
authurl = "http://<ip>/LoadTest/rest/authentication-point/authenticate"
r = session.get(authurl, headers=headers)
print r.status_code

设置trust_env=False 会忽略以下内容:

  • 来自 .netrc 的认证信息(代码)
  • CA 捆绑包定义在 REQUESTS_CA_BUNDLE 或 CURL_CA_BUNDLE(代码)

【讨论】:

    猜你喜欢
    • 2021-12-14
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多