如何在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
相关产品推荐
相关产品推荐

