如何将代理身份验证传递给 python 请求模块

Fed*_*ico 6 python authentication proxy python-requests

我正在处理使用请求模块执行获取/发布到网站的现有 python 代码。

python 代码还允许在将代理传递给脚本时使用代理,否则不使用代理。

我的问题是关于使用需要身份验证的代理。

proxy = user:password@ip:port
self.s = requests.Session()
if proxy != "":
      self.proxies = {
        "http": "http://" + proxy,
        "https": "https://" + proxy
      }
      self.s.proxies.update(proxies)

self.s.get('http://checkip.dyndns.org')
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,如果配置了代理,每个get 都会被拒绝,因为没有提供身份验证。

我找到了一个暗示使用 HTTPProxyAuth 的解决方案。

这是我找到的解决方案:

import requests
s = requests.Session()

proxies = {
  "http": "http://ip:port",
  "https": "https://ip:port"
}

auth = HTTPProxyAuth("user", "pwd")
ext_ip = s.get('http://checkip.dyndns.org', proxies=proxies, auth=auth)
print ext_ip.text
Run Code Online (Sandbox Code Playgroud)

我的问题是:是否可以全局设置代理授权而不是修改代码中的每个s.get?因为有时脚本可以在没有代理的情况下使用,有时也可以使用代理。

提前致谢!

最好的问候,费德里科

Fed*_*ico 12

我找到了解决方案,关于如何全局设置代理身份验证:

import requests
import urllib2
import re
from requests.auth import HTTPProxyAuth

s = requests.Session()

proxies = {
  "http": "http://185.165.193.208:8000",
  "https": "https://185.165.193.208:8000"
}

auth = HTTPProxyAuth("gRRT7n", "NMu8g0")

s.proxies = proxies
s.auth = auth        # Set authorization parameters globally

ext_ip = s.get('http://checkip.dyndns.org')
print ext_ip.text
Run Code Online (Sandbox Code Playgroud)

BR,费德里科