httpx我正在使用一个用于发出请求的模块。由于我公司的网络政策,CERTIFICATE_VERIFY_FAILED每次我尝试运行我的代码时都会得到一个。我在请求中发送和接收的数据不敏感,所以我想禁用模块上的 SSL 验证。

如果我要编写请求,我可以这样使用会话:

client = httpx.Client(**kwargs, verify=False)

但是请求在模块内部。

Blender对这个堆栈溢出答案做出了很好的回应,他们用下面的代码编写了一个上下文管理器,但该代码不适用于该httpx模块:

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):
        # Verification happens only once per connection so we need to close
        # all the opened adapters once we're done. Otherwise, the effects of
        # verify=False persist beyond the end of this context manager.
        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

有没有一种方法可以在通过 httpx 发出的请求中复制相同的行为?


在模块使用时工作httpx.Client

import contextlib


@contextlib.contextmanager
def no_ssl_verification():
    """Context manager to disable SSL verification on httpx Client.
    """
    import httpx

    # Save original Client constructor
    Client = httpx.Client

    # Disable SSL verification
    httpx.Client = lambda *args, **kwargs: Client(*args, verify=False, **kwargs)

    # Yield control to the caller
    yield

    # Restore original verify value
    httpx.Client = Client

禁用证书(不是“SSL”)验证意味着你基本上失去了使用 HTTPS 的所有好处,然后你应该停止假装拥有任何安全性,因此回到纯 HTTP,因为实际上这就是你所拥有的。

这是一个网络抓取器,数据不敏感,但我从中抓取的网站总是重定向到 https,公司的网络监控使用自签名证书拦截连接以监控网络,从而破坏了代码。如果可以的话,我会使用纯 HTTP。