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

ssl.PROTOCOL_TLSv1_2已弃用,如何消除Python代码中的警告?

解决ssl.PROTOCOL_TLSv1_2弃用警告的方案

你遇到的警告是因为硬指定TLSv1.2版本已被Python弃用,没必要手动锁定旧版本协议,Python的ssl模块默认会支持安全的TLS版本协商,以下两种方案都能消除警告:

方案一:使用默认SSL上下文(推荐,最简便)

直接删除手动创建SSLContext的代码,urlopen会自动使用默认的安全上下文,自动适配当前环境支持的最优TLS版本。修改后的代码如下:

import io
from urllib import request

item_image = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/180px-Cat03.jpg"
    
f = io.BytesIO(request.urlopen(item_image).read())

如果你想显式声明默认上下文,也可以这么写:

import io
import ssl
from urllib import request

# 创建默认安全上下文,自动启用所有兼容的安全TLS版本
context = ssl.create_default_context()
item_image = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/180px-Cat03.jpg"
    
f = io.BytesIO(request.urlopen(item_image, context=context).read())

方案二:正确使用PROTOCOL_TLS_CLIENT

之前替换后无效,是因为PROTOCOL_TLS_CLIENT模式要求必须配置server_hostname(用于SNI扩展),不能直接沿用旧写法。修改后的代码如下:

import io
import ssl
from urllib import request
from urllib.parse import urlparse

context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
# 必须开启主机名检查和证书验证
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
# 加载系统默认CA证书
context.load_default_certs()

item_image = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/180px-Cat03.jpg"
# 从URL中解析主机名,或直接写"upload.wikimedia.org"
hostname = urlparse(item_image).hostname
    
f = io.BytesIO(request.urlopen(item_image, context=context, server_hostname=hostname).read())

这种方式相对繁琐,仅在有特殊定制需求时使用。

运行上述任一修改后的代码,DeprecationWarning就会消失,同时能正常获取图片。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 20:57:23