Python requests库将HTTPProxyAuth与HTTPBasicAuth结合使用

4 投票
3 回答
4608 浏览
提问于 2025-04-17 11:10

在这里找到了一个关于HTTPProxyAuth用法的例子 https://stackoverflow.com/a/8862633

不过我希望能有一个例子,展示如何同时使用HTTPProxyAuth和HTTPBasicAuth。也就是说,我需要通过代理传递一个服务器地址、用户名和密码,同时还要给网页传递一个用户名和密码……

提前谢谢你。

理查德

3 个回答

0

这方法看起来不太好,但你可以在代理和受限页面的链接中分别提供基本认证的账号和密码。

举个例子:

proxies = {
 "http": "http://myproxyusername:mysecret@webproxy:8080/",
 "https": "http://myproxyusername:mysecret@webproxy:8080/",
}

r = requests.get("http://mysiteloginname:myothersecret@mysite.com", proxies=proxies)
0

很遗憾,HTTPProxyAuthHTTPBasicAuth 的一个子类,它会改变父类的行为(具体可以查看 requests/auth.py 文件)。

不过,你可以通过创建一个新的类来同时实现这两种功能,从而在请求中添加所需的头信息:

class HTTPBasicAndProxyAuth:
    def __init__(self, basic_up, proxy_up):
        # basic_up is a tuple with username, password
        self.basic_auth = HTTPBasicAuth(*basic_up)
        # proxy_up is a tuple with proxy username, password
        self.proxy_auth = HTTPProxyAuth(*proxy_up)

    def __call__(self, r):
        # this emulates what basicauth and proxyauth do in their __call__()
        # first add r.headers['Authorization']
        r = self.basic_auth(r)
        # then add r.headers['Proxy-Authorization']
        r = self.proxy_auth(r)
        # and return the request, as the auth object should do
        return r
1

对于基本认证,你可以使用Python的Httplib2模块。下面给出了一个例子。想了解更多细节,可以查看这个链接

>>>import httplib2

>>>h = httplib2.Http(".cache")

>>>h.add_credentials('name', 'password')

>>>resp, content = h.request("https://example.org/chap/2", 
"PUT", body="This is text", 
headers={'content-type':'text/plain'} )

我觉得Httplib2并不支持代理功能。可以查看这个链接

撰写回答