在我的项目中,我使用 python requests
library 处理所有 HTTP 请求。
现在,我需要使用特定的 DNS 查询 http 服务器 - 有两个环境,每个环境都使用自己的 DNS,并且独立进行更改。
因此,当代码运行时,它应该使用特定于环境的 DNS,而不是在我的互联网连接中指定的 DNS。
有没有人使用 python-requests 尝试过这个?我只找到了 urllib2 的解决方案:
https://stackoverflow.com/questions/4623090/python-set-custom-dns-server-for-urllib-requests
原文由 Taku 发布,翻译遵循 CC BY-SA 4.0 许可协议
requests
使用urllib3
,最终使用httplib.HTTPConnection
以及,所以来自https: //stackions-setonquest03custompythover4.com2 的技术-dns-server-for-urllib-requests (现已删除,它仅链接到 Tell urllib2 to use custom DNS )在一定程度上仍然适用。The
urllib3.connection
module subclasseshttplib.HTTPConnection
under the same name, having replaced the.connect()
method with one that callsself._new_conn
.反过来,这委托给urllib3.util.connection.create_connection()
。修补 该 功能可能是最简单的方法:并且您将提供自己的代码来将地址的
host
部分解析为 IP 地址,而不是依赖于connection.create_connection()
调用(包装socket.create_connection()
)为您解析主机名。像所有的 monkeypatching 一样,请注意代码在以后的版本中没有发生重大变化;此处的补丁是针对
urllib3
版本 1.21.1 创建的。但应该适用于早至 1.9 的版本。请注意,此答案已重新编写以与更新的
urllib3
版本一起使用,这些版本添加了一个更方便的修补位置。请参阅旧方法的编辑历史,适用于 < 1.9 版本,作为 vendoredurllib3
版本的补丁而不是独立安装。