在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中文網其他相關文章!