How to Disable Certificate Verification in Python Requests?

Mary-Kate Olsen
Release: 2024-10-26 15:38:03
Original
813 people have browsed it

How to Disable Certificate Verification in Python Requests?

Disable Certificate Verification in Python Requests

When encountering an expired certificate error while making HTTPS requests with requests, a common solution is to disable the security certificate check.

Solution 1: Using verify=False

As mentioned in the documentation, you can pass verify=False to disable certificate verification.

<code class="python">import requests
requests.post(url='https://foo.example', data={'bar':'baz'}, verify=False)</code>
Copy after login

Solution 2: Monkey Patching requests (Context Manager)

For more advanced usage, you can use a context manager to monkey patch requests and disable certificate verification for all requests within the context.

<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>
Copy after login

Usage:

<code class="python">with no_ssl_verification():
    requests.get('https://wrong.host.badssl.example/')</code>
Copy after login

Note that this context manager closes all open adapters after leaving it to avoid unexpected behavior due to cached connections.

The above is the detailed content of How to Disable Certificate Verification in Python Requests?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template