Python请求库将HTTPProxyAuth与HTTPBasicAuth结合在一起

时间:2012-01-26 22:00:13

标签: python proxy http-request python-requests

在此处找到有关HTTPProxyAuth用法的示例https://stackoverflow.com/a/8862633

但我希望有关HTTPProxyAuth和HTTPBasicAuth IE的使用示例,我需要通过代理将用户名和密码以及用户名和密码传递到网页...

提前致谢。

理查德

3 个答案:

答案 0 :(得分:1)

对于基本身份验证,您可以使用python的Httplib2模块。下面给出一个例子。有关详细信息,请查看this

>>>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提供代理支持。检查link -

答案 1 :(得分: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

答案 2 :(得分:0)

它不漂亮,但您可以在代理服务器和受限制的网页网址中提供单独的BasicAuth凭据。

例如:

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

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