Python请求库结合了HTTPProxyAuth和HTTPBasicAuth

2024-05-13 04:22:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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

但我希望有一个关于HTTPProxyAuth和HTTPBasicAuth的使用示例,即我需要通过代理传递服务器、用户名和密码以及网页的用户名和密码。。。在

提前谢谢。在

理查德


Tags: https服务器com网页密码示例代理用法
3条回答

不幸的是,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

这并不漂亮,但您可以在代理和受限制的页面url中提供单独的BasicAuth凭据。

例如:

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

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

对于基本身份验证,可以使用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-

相关问题 更多 >