在我的项目中,我使用 python 处理所有 HTTP 请求 requests
library .
现在,我需要使用特定的 DNS 查询 http 服务器 - 有两个环境,每个环境都使用自己的 DNS,并且独立进行更改。
因此,当代码运行时,它应该使用特定于环境的 DNS,而不是在我的互联网连接中指定的 DNS。
有没有人用 python-requests 试过这个?我只找到了 urllib2 的解决方案:
https://stackoverflow.com/questions/4623090/python-set-custom-dns-server-for-urllib-requests
最佳答案
requests
使用 urllib3
,它最终也使用 httplib.HTTPConnection
,因此来自 https://stackoverflow 的技术。 com/questions/4623090/python-set-custom-dns-server-for-urllib-requests(现已删除,它仅链接到 Tell urllib2 to use custom DNS)在一定程度上仍然适用。
urllib3.connection
模块子类 httplib.HTTPConnection
同名,用调用方法替换了 .connect()
方法self._new_conn
。反过来,这委托(delegate)给 urllib3.util.connection.create_connection()
。修补那个函数可能是最简单的:
from urllib3.util import connection
_orig_create_connection = connection.create_connection
def 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 一样,请注意代码在以后的版本中没有发生重大变化;此处的补丁是针对 urllib3
版本 1.21.1 创建的。但应该适用于早至 1.9 的版本。
请注意,此答案已重新编写以与较新的 urllib3
版本一起使用,这些版本添加了一个更方便的修补位置。请参阅旧方法的编辑历史记录,适用于 < 1.9 版,作为销售 urllib3
版本的补丁而不是独立安装。
关于Python 'requests' 库 - 定义特定的 DNS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32654092/