Python用aiohttp异步请求API触发ClientConnectorCertificateError是什么原因
错误触发原因
该ClientConnectorCertificateError属于SSL证书校验失败类错误,触发逻辑是aiohttp发送HTTPS请求时,无法在运行环境的根证书库中匹配到swapi.dev站点SSL证书的颁发机构根证书,无法完成证书信任链校验,因此主动终止了连接请求。
常见触发场景:
- macOS系统下通过Python官方安装包安装的Python,默认未预置根证书库,无法完成校验
- 本地网络存在代理、防火墙设备,篡改了HTTPS请求的返回证书
- 系统根证书库长期未更新,缺少对应根证书
修复方案
临时调试方案(仅本地验证用,禁止生产环境使用)
修改ClientSession初始化参数,关闭SSL证书校验即可:
import aiohttp import asyncio import time async def index(request): start_time = time.time() url = 'https://swapi.dev/api/starships/9/' # 新增TCPConnector配置关闭ssl校验 async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as client: task = asyncio.ensure_future(fetch(client, url)) results = await asyncio.gather(task) total = time.time() - start_time print(total) return render(request, 'index.html', {'results':results })
正式修复方案
根据运行环境选择对应操作修复根证书配置即可:
- macOS Python官方安装版本:运行Python安装目录下的
Install Certificates.command脚本,自动安装预置根证书库 - Debian/Ubuntu Linux:执行命令
apt install ca-certificates && update-ca-certificates更新系统根证书库 - CentOS/RHEL Linux:执行命令
yum install ca-certificates && update-ca-trust force-enable更新系统根证书库 - 也可自行下载公共CA根证书包,在ClientSession初始化时传入证书路径
ssl="/path/to/your/ca_bundle.pem"完成校验
内容的提问来源于stack exchange,提问作者paul385mi
相关产品推荐
相关产品推荐

