You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在使用httpx的第三方模块中禁用SSL验证

问题

使用基于httpx的第三方模块时,受公司网络政策限制,每次运行代码都会触发CERTIFICATE_VERIFY_FAILED错误。由于请求收发的数据不敏感,希望禁用SSL验证,但请求逻辑由第三方模块内部实现,无法直接在创建客户端时传入verify=False参数。

此前看到过适用于requests模块的上下文管理器,但无法直接用于httpx,因此需要一个类似的、针对httpx的上下文管理器实现。

解决方案

可以通过猴子补丁的方式,实现针对httpx的上下文管理器,强制第三方模块创建的所有httpx客户端禁用SSL验证,同时在上下文结束后恢复原始行为:

import warnings
import contextlib
import httpx
from httpx import InsecureRequestWarning

# 保存原始的同步/异步客户端初始化方法
old_sync_client_init = httpx.Client.__init__
old_async_client_init = httpx.AsyncClient.__init__

@contextlib.contextmanager
def no_ssl_verification():
    # 重写客户端初始化方法,强制设置verify=False
    def patched_sync_init(self, *args, **kwargs):
        kwargs["verify"] = False
        old_sync_client_init(self, *args, **kwargs)
    
    def patched_async_init(self, *args, **kwargs):
        kwargs["verify"] = False
        old_async_client_init(self, *args, **kwargs)
    
    # 替换原始初始化逻辑
    httpx.Client.__init__ = patched_sync_init
    httpx.AsyncClient.__init__ = patched_async_init
    
    try:
        # 忽略不安全请求的警告
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", InsecureRequestWarning)
            yield
    finally:
        # 恢复原始的初始化方法,避免影响上下文外的代码
        httpx.Client.__init__ = old_sync_client_init
        httpx.AsyncClient.__init__ = old_async_client_init

使用方式

将第三方模块的请求逻辑放在上下文管理器内部执行即可:

with no_ssl_verification():
    # 调用第三方模块的请求方法
    third_party_module.run_requests()

注意事项

  • 仅在数据无敏感信息的场景下使用,禁用SSL验证会导致请求失去证书校验的安全保障
  • 上下文管理器仅对其内部执行的httpx请求生效,不会影响外部的httpx客户端行为
  • 同时支持同步(httpx.Client)和异步(httpx.AsyncClient)两种客户端类型

内容的提问来源于stack exchange,提问作者João Areias

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 03:57:33