解决 Python 中 API 证书验证失败问题

解决 Python 中 API 证书验证失败问题

我正在运行几个使用 Python 的应用程序。无论使用哪个应用程序(即使我直接在 Python 本身中执行脚本),证书验证总是会失败,代码如下:

File "/usr/local/lib/python3.11/urllib/request.py", line 1348, in do_open
    h.request(req.get_method(), req.selector, req.data, headers,
  File "/usr/local/lib/python3.11/http/client.py", line 1282, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/usr/local/lib/python3.11/http/client.py", line 1328, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/usr/local/lib/python3.11/http/client.py", line 1277, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/usr/local/lib/python3.11/http/client.py", line 1037, in _send_output
    self.send(msg)
  File "/usr/local/lib/python3.11/http/client.py", line 975, in send
    self.connect()
  File "/usr/local/lib/python3.11/http/client.py", line 1454, in connect
    self.sock = self._context.wrap_socket(self.sock,
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/ssl.py", line 517, in wrap_socket
    return self.sslsocket_class._create(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/ssl.py", line 1075, in _create
    self.do_handshake()
  File "/usr/local/lib/python3.11/ssl.py", line 1346, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)

我多次安装了 certifi,重新安装了 OpenSSL、python、pip 和应用程序本身,手动为网站创建了证书并将它们放在证书文件夹中……但都无法解决这个问题。我没有使用 VPN。您是如何解决此错误的?

答案1

我最终能够通过导入 ssl 并创建未经验证的上下文来强制程序在 python 中运行。

import ssl
ssl._create_default_https_context = ssl._create_unverified_context

证书问题仍然没有解决,但至少我可以继续前进。

相关内容