ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997)

Question:

I was playing with some web frameworks for Python, when I tried to use the framework aiohhtp with this code (taken from the documentation):

import aiohttp
import asyncio

#********************************
# a solution I found on the forum:
# https://stackoverflow.com/questions/50236117/scraping-ssl-certificate-verify-failed-error-for-http-en-wikipedia-org?rq=1
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
# ... but it doesn't work :(
#********************************

async def main():

    async with aiohttp.ClientSession() as session:
        async with session.get("https://python.org") as response:

            print("Status:", response.status)
            print("Content-type:", response.headers["content-type"])

            html = await response.text()
            print("Body:", html[:15], "...")

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

When I run this code I get this traceback:

DeprecationWarning: There is 
no current event loop
  loop = asyncio.get_event_loop()
Traceback (most recent call last):
  File "c:Python310libsite-packagesaiohttpconnector.py", line 986, in _wrap_create_connection
    return await self._loop.create_connection(*args, **kwargs)  # type: ignore[return-value]  # noqa
  File "c:Python310libasynciobase_events.py", line 1080, in create_connection
    transport, protocol = await self._create_connection_transport(
  File "c:Python310libasynciobase_events.py", line 1110, in _create_connection_transport
    await waiter
  File "c:Python310libasynciosslproto.py", line 528, in data_received
    ssldata, appdata = self._sslpipe.feed_ssldata(data)
  File "c:Python310libasynciosslproto.py", line 188, in feed_ssldata
    self._sslobj.do_handshake()
  File "c:Python310libssl.py", line 974, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997)    

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "c:UserschrisDocumentsProgrammi_in_Python_offlineEsercitazioniPython_commandsaioWebTest.py", line 21, in <module>   
    loop.run_until_complete(main())
  File "c:Python310libasynciobase_events.py", line 641, in run_until_complete
    return future.result()
  File "c:UserschrisDocumentsProgrammi_in_Python_offlineEsercitazioniPython_commandsaioWebTest.py", line 12, in main       
    async with session.get("https://python.org") as response:
  File "c:Python310libsite-packagesaiohttpclient.py", line 1138, in __aenter__
    self._resp = await self._coro
  File "c:Python310libsite-packagesaiohttpclient.py", line 535, in _request
    conn = await self._connector.connect(
  File "c:Python310libsite-packagesaiohttpconnector.py", line 542, in connect
    proto = await self._create_connection(req, traces, timeout)
  File "c:Python310libsite-packagesaiohttpconnector.py", line 907, in _create_connection
    _, proto = await self._create_direct_connection(req, traces, timeout)
  File "c:Python310libsite-packagesaiohttpconnector.py", line 1206, in _create_direct_connection
    raise last_exc
  File "c:Python310libsite-packagesaiohttpconnector.py", line 1175, in _create_direct_connection
    transp, proto = await self._wrap_create_connection(
  File "c:Python310libsite-packagesaiohttpconnector.py", line 988, in _wrap_create_connection
    raise ClientConnectorCertificateError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host python.org:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997)')]

From the final row I have thought that it was a problem with a certificate that is expired, so I searched on the internet and I tried to solve installing some certificates:

I’m sorry for the long question, but I searched a lot on the internet and I couldn’t find the solution for my case.
Thank you in advance, guys <3

Asked By: Seintian

||

Answers:

Picking up on the comment by @salparadise, the following worked for me:

session.get("https://python.org", ssl=False)

Edit (2023-03-10):

I’ve run into this problem again and have found this answer to a similar question, which provides a much better long-term solution.

In short: use the certificates in the certifi package to create the aiohttp client session (as @salparadise also suggested earlier). You’ll find the code to do so at the link above. It worked for me just as well as disabling ssl, and is of course a much better way of solving the problem.

Answered By: Andras Kiss