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

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

Barbara Streisand
Barbara Streisand原創
2024-10-29 00:15:30774瀏覽

How to Disable Security Certificate Verification in Python Requests?

在Python 請求中停用安全憑證驗證

使用Python 請求庫與HTTPS 端點互動時,您可能會遇到與無效SSL相關的錯誤證書。為了緩解這個問題,您可以在請求中停用憑證驗證。

根據官方文檔,您可以透過將 verify 參數設為 False 來實現此目的。這指示請求繞過憑證驗證。

<code class="python">import requests

requests.post(url='https://foo.example', data={'bar': 'baz'}, verify=False)</code>

或者,對於可能處理 SSL 驗證的第三方模組,您可以使用上下文管理器來抑制警告並停用驗證。這涉及將 requests.Session.merge_environment_settings 方法替換為預設將 verify 設為 False 的自訂版本。

<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/')
    print('It works')

requests.get('https://wrong.host.badssl.example/', verify=False)
print('It resets back')</code>

它值得注意的是,此解決方案會影響上下文管理器範圍內發出的所有請求。因此,除非明確指定,後續請求也將繞過憑證驗證。

以上是如何在Python請求中停用安全憑證驗證?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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