解决MacOS中Python3环境请求https报错的问题

发现问题

在使用腾讯云开发者工具套件(SDK)3.0过程中,遇到证书错误:

Error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1056).

此时查看腾讯云官方文档,发现说明:

证书问题
  在Mac操作系统安装Python 3.6或更高版本时,可能会遇到证书错误:Error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1056).。这是因为在Mac操作系统下,Python不再使用系统操作系统的证书,且本身也不提供证书。 ,需要使用certifi库提供的证书,但SDK不支持指定,所以只能使用sudo "/Applications/Python 3.6/Install Certificates.command"命令安装证书才能解决此问题。
    虽然Python 2版本不应该有同样的问题,但是在个别用户环境上确实也观察到有类似的情况,也一样可以通过sudo /Applications/Python 2.7/Install Certificates.command解决。


但是我安装python版本在Application中并未找到Python3.x 文件夹
找不到命令

注:通过homebrew工具安装的python3版本理论均找不到该文件夹

解决方案

通过反复爬贴:在stackoverflow找到一篇解决方案:原帖链接

stackoverflow截图

该文章提到:通过brew安装的python版本不包括这个脚本命令

所以新建 install_certifi.py 文件,粘贴以下代码(该文件已放在本博客结尾附件中):

# install_certifi.py
#
# sample script to install or update a set of default Root Certificates
# for the ssl module.  Uses the certificates provided by the certifi package:
#       https://pypi.python.org/pypi/certifi

import os
import os.path
import ssl
import stat
import subprocess
import sys

STAT_0o775 = ( stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
             | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP
             | stat.S_IROTH |                stat.S_IXOTH )


def main():
    openssl_dir, openssl_cafile = os.path.split(
        ssl.get_default_verify_paths().openssl_cafile)

    print(" -- pip install --upgrade certifi")
    subprocess.check_call([sys.executable,
        "-E", "-s", "-m", "pip", "install", "--upgrade", "certifi"])

    import certifi

    # change working directory to the default SSL directory
    os.chdir(openssl_dir)
    relpath_to_certifi_cafile = os.path.relpath(certifi.where())
    print(" -- removing any existing file or link")
    try:
        os.remove(openssl_cafile)
    except FileNotFoundError:
        pass
    print(" -- creating symlink to certifi certificate bundle")
    os.symlink(relpath_to_certifi_cafile, openssl_cafile)
    print(" -- setting permissions")
    os.chmod(openssl_cafile, STAT_0o775)
    print(" -- update complete")

if __name__ == '__main__':
    main()

并在终端中执行

sudo python3 install_certifi.py

运行过程和结果

再次调用腾讯云开发者工具套件方法,执行成功!
再次运行,执行成功

本文章解决方案来自 :https://stackoverflow.com/questions/44649449/brew-installation-of-python-3-6-1-ssl-certificate-verify-failed-certificate

附件📎:install_certifi.py

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×