首頁  >  文章  >  後端開發  >  如何在Python請求中停用憑證驗證?

如何在Python請求中停用憑證驗證?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-26 15:38:03754瀏覽

How to Disable Certificate Verification in Python Requests?

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn