问题:
requests调用huobi接口时,总是提示:HTTPSConnectionPool(host='api.huobi.pro', port=443): Max retries exceeded with url: /v2/settings/common/symbols?ts=1683653443 (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0000000003311FA0>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。'))
我的proxy配置为:
proxy_ip = 'localhost:12345'
my_proxies = {
'http': 'http://' + proxy_ip,
}
先说结论:
我的proxy为http的,但是我调用的接口为https的,所以此时需要增加一个https的key或者直接修改为http的,我的理解是:调用的接口的协议是什么,proxy配置中的key就应该是什么,此时proxy的配置的key可以只有https,如果为了防止以后有http协议的接口,也可以把保留proxy中key为http的配置。
proxy_ip = 'localhost:12345'
my_proxies = {
'http': 'http://' + proxy_ip,
'https': 'http://' + proxy_ip,
}
在debug到adapters.py中时,发现有一段选择proxy的代码
proxy = select_proxy(request.url, proxies)
继续跟踪,进入了requests\utils.py中:
def select_proxy(url, proxies):
"""Select a proxy for the url, if applicable.
:param url: The url being for the request
:param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
"""
proxies = proxies or {}
urlparts = urlparse(url)
if urlparts.hostname is None:
return proxies.get(urlparts.scheme, proxies.get("all"))
proxy_keys = [
urlparts.scheme + "://" + urlparts.hostname,
urlparts.scheme,
"all://" + urlparts.hostname,
"all",
]
proxy = None
for proxy_key in proxy_keys:
if proxy_key in proxies:
proxy = proxies[proxy_key]
break
return proxy
urlparts内容为:
ParseResult(scheme='https', netloc='api.huobi.pro',
path='/v2/settings/common/symbols', params='', query='ts=1683654234', fragment='')
proxy_keys内容为:
['https://api.huobi.pro', 'https', 'all://api.huobi.pro', 'all']
proxies内容为:
OrderedDict([('http', 'http://localhost:12345'), ('https', 'http://localhost:12345')])
当proxy_key为https时,proxy=http://localhost:12345,同时跳出循环,并继续执行请求。