aiohttp 异步http请求-7.https请求报SSL问题
前言
默认情况下, aiohttp对 HTTPS 协议使用严格检查。有些同学电脑上请求https请求可能会报ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED]
SLL 证书校验
当我们访问一个https请求
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('https://www.cnblogs.com/yoyoketang/') as resp:
print(resp.url)
print(await resp.read())
# asyncio.run(main()) # 会报错,改成下面2句
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
如果出现SSL证书校验问题:ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED]
只需加一个将 ssl 参数设置为来忽略认证检查 ssl=False
async with aiohttp.ClientSession() as session:
async with session.get('https://www.cnblogs.com/yoyoketang/', ssl=False) as resp:
传本地证书
如果你本地有ssl证书,证书地址为/path/to/ca-bundle.crt
, 可以传本地证书
sslcontext = ssl.create_default_context(
cafile='/path/to/ca-bundle.crt')
r = await session.get('https://example.com', ssl=sslcontext)
如果您需要验证自签名ssl.SSLContext.load_cert_chain()证书,您可以执行与上一个示例相同的操作,但使用密钥对添加另一个调用 :
sslcontext = ssl.create_default_context(
cafile='/path/to/ca-bundle.crt')
sslcontext.load_cert_chain('/path/to/client/public/device.pem',
'/path/to/client/private/device.key')
r = await session.get('https://example.com', ssl=sslcontext)
在 ClientSession 设置忽略证书
我们也可以在创建ClientSession 会话的时候设置ssl=False
全局参数
conn = aiohttp.TCPConnector(ssl=False)
async with aiohttp.ClientSession(connector=conn) as session:
async with session.get('https://www.cnblogs.com/yoyoketang/') as resp:
print(resp.url)
print(await resp.read())
verify_ssl=False
早期的版本会看到verify_ssl=False
conn = aiohttp.TCPConnector(verify_ssl=False)
async with aiohttp.ClientSession(connector=conn) as session:
async with session.get('https://www.cnblogs.com/yoyoketang/') as resp:
print(resp.url)
print(await resp.read())
此时会有警告,提示我们用最新的语法ssl=False
代替原来的'verify_ssl=False`
DeprecationWarning: verify_ssl is deprecated, use ssl=False instead
conn = aiohttp.TCPConnector(verify_ssl=False)