该
urllib3.connection模块
httplib.HTTPConnection以相同的名称子类化,已用
.connect()调用的方法替换了该方法
self._new_conn。反过来,这委托给
urllib3.util.connection.create_connection()。修补
该 功能可能是最简单的:
from urllib3.util import connection_orig_create_connection = connection.create_connectiondef patched_create_connection(address, *args, **kwargs): """Wrap urllib3's create_connection to resolve the name elsewhere""" # resolve hostname to an ip address; use your own # resolver here, as otherwise the system resolver will be used. host, port = address hostname = your_dns_resolver(host) return _orig_create_connection((hostname, port), *args, **kwargs)connection.create_connection = patched_create_connection
并且您将提供自己的代码来
host将地址的一部分解析为ip地址,而不是依靠
connection.create_connection()调用(自动包装
socket.create_connection())为您解析主机名。
像所有的monkeypatching一样,请注意,在以后的版本中代码没有显着更改;该补丁是针对
urllib31.21.1版创建的。但应该适用于1.9之前的版本。
请注意,此答案已重新编写以与较新的urllib3
版本一起使用,这些新版本添加了更方便的修补位置。请参阅适用于版本<1.9的旧方法的编辑历史记录,以作为供应商urllib3
版本的补丁程序,而不是独立安装。



