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

在SSLContext中使用Kubernetes Secrets加载证书的替代方案咨询

适用方案

你的需求完全可以实现,根据你使用的Python版本可以选择两种不同的实现方式:


方案1:Python 3.12及以上版本(原生支持内存加载,无需写本地文件)

从Python 3.12版本开始,ssl.SSLContext.load_cert_chain新增了cert、key入参,支持直接传入字节类型的证书、私钥内容,不需要传入本地文件路径,代码示例如下:

import ssl
import http.client

# 已从K8s获取到的证书、密钥字符串先转成字节格式
cert_bytes = CERT.encode("utf-8")
key_bytes = KEY.encode("utf-8")
pw_bytes = PW.encode("utf-8") if PW else None

# Define the client certificate settings for https connection
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.load_cert_chain(
    cert=cert_bytes,
    key=key_bytes,
    password=pw_bytes
)
 
# 后续请求逻辑保持不变
connection = http.client.HTTPSConnection(host, port=443, context=context)
connection.request(method="GET", url=request_url, headers=request_headers)
response = connection.getresponse()
print(response.status, response.reason)
data = response.read()
print(data)

方案2:Python 3.11及以下版本(用临时文件实现)

如果你的运行环境Python版本低于3.12,可以用临时目录存储证书密钥,使用结束后临时文件会自动删除,适合POC场景使用,代码示例如下:

import ssl
import http.client
import tempfile
import os

context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)

# 创建自动清理的临时目录
with tempfile.TemporaryDirectory() as tmp_dir:
    # 写入证书临时文件
    cert_path = os.path.join(tmp_dir, "client.crt")
    with open(cert_path, "w", encoding="utf-8") as f:
        f.write(CERT)
    # 写入私钥临时文件
    key_path = os.path.join(tmp_dir, "client.key")
    with open(key_path, "w", encoding="utf-8") as f:
        f.write(KEY)
    
    # 加载证书
    context.load_cert_chain(certfile=cert_path, keyfile=key_path, password=PW)
    
    # 后续请求逻辑放在with块内即可,执行结束后临时文件会自动删除
    connection = http.client.HTTPSConnection(host, port=443, context=context)
    connection.request(method="GET", url=request_url, headers=request_headers)
    response = connection.getresponse()
    print(response.status, response.reason)
    data = response.read()
    print(data)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 21:06:07