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

如何在Python requests Session中使用truststore的SSLContext?

在requests.Session中使用truststore的实现示例

truststore曾支持全局注入上下文的使用方式,但维护者近期更新明确不建议这种全局操作,以下是针对requests.Session对象的局部配置方案:

前置准备

确保安装最新版truststore:

pip install --upgrade truststore

实现代码

通过自定义HTTP适配器,将truststore的SSL上下文绑定到指定的requests.Session对象:

import requests
import truststore
from requests.adapters import HTTPAdapter
from urllib3.poolmanager import PoolManager

class TruststoreAdapter(HTTPAdapter):
    def init_poolmanager(self, *args, **kwargs):
        # 用truststore创建SSL上下文
        ssl_ctx = truststore.SSLContext()
        kwargs["ssl_context"] = ssl_ctx
        return super().init_poolmanager(*args, **kwargs)

# 创建Session并挂载适配器
session = requests.Session()
# 为所有HTTPS请求应用truststore证书验证
session.mount("https://", TruststoreAdapter())

# 测试使用
resp = session.get("https://example.com")
print(resp.status_code)

说明

  • 自定义适配器仅作用于当前session对象,不会影响全局SSL配置,符合官方不建议全局注入的要求。
  • 若需仅对特定域名生效,可修改mount的前缀,例如:
    # 仅针对api.example.com的请求使用truststore
    session.mount("https://api.example.com", TruststoreAdapter())
    

内容的提问来源于stack exchange,提问作者JabberJabber

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 08:05:00