在 Python 请求中禁用证书验证
当使用 requests 发出 HTTPS 请求时遇到证书过期错误时,常见的解决方案是禁用安全证书检查。
解决方案 1:使用 verify=False
如文档中所述,您可以通过 verify=False 禁用证书验证。
<code class="python">import requests requests.post(url='https://foo.example', data={'bar':'baz'}, verify=False)</code>
解决方案 2:猴子修补请求(上下文管理器)
对于更高级的用法,您可以使用上下文管理器来猴子修补请求并禁用所有请求的证书验证
<code class="python">import warnings import contextlib import requests from urllib3.exceptions import InsecureRequestWarning old_merge_environment_settings = requests.Session.merge_environment_settings @contextlib.contextmanager def no_ssl_verification(): opened_adapters = set() def merge_environment_settings(self, url, proxies, stream, verify, cert): opened_adapters.add(self.get_adapter(url)) settings = old_merge_environment_settings(self, url, proxies, stream, verify, cert) settings['verify'] = False return settings requests.Session.merge_environment_settings = merge_environment_settings try: with warnings.catch_warnings(): warnings.simplefilter('ignore', InsecureRequestWarning) yield finally: requests.Session.merge_environment_settings = old_merge_environment_settings for adapter in opened_adapters: try: adapter.close() except: pass</code>
用法:
<code class="python">with no_ssl_verification(): requests.get('https://wrong.host.badssl.example/')</code>
请注意,此上下文管理器在离开后会关闭所有打开的适配器,以避免由于缓存连接而导致意外行为。
以上是如何在Python请求中禁用证书验证?的详细内容。更多信息请关注PHP中文网其他相关文章!