python请求转换为.exe时找不到带有证书的文件夹

Posted

技术标签:

【中文标题】python请求转换为.exe时找不到带有证书的文件夹【英文标题】:python requests can't find a folder with a certificate when converted to .exe 【发布时间】:2018-02-17 13:58:23 【问题描述】:

我有一个程序可以汇集来自不同营销系统的广告统计信息。一切正常,直到我将其转换为 .exe 格式并运行它。

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 1549, in __call__
    return self.func(*args)
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\report_gui.py", line 24, in <lambda>
    ok = tk.Button(root, text="DO NOT PRESS", bg="red", command=lambda: self.run())
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\report_gui.py", line 43, in run
    report.merge_all()
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\process_data.py", line 400, in merge_all
    fb_df     = self.fetch_fb()
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\process_data.py", line 156, in fetch_fb
    fb_campaigns = from_fb.run_fb(self.start_date, self.end_date)  # in JSON format
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\from_fb.py", line 110, in run_fb
    return s.get_stats()
  File "C:\Users\user\Desktop\alg\TSK_7. Marketing\from_fb.py", line 84, in get_stats
    params=params,
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\facebookads\adobjects\adaccount.py", line 1551, in get_insights
    return request.execute()
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\facebookads\api.py", line 653, in execute
    cursor.load_next_page()
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\facebookads\api.py", line 797, in load_next_page
    params=self.params,
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\facebookads\api.py", line 305, in call
    timeout=self._session.timeout
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\adapters.py", line 407, in send
    self.cert_verify(conn, request.url, verify, cert)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\adapters.py", line 226, in cert_verify
    "invalid path: 0".format(cert_loc))
OSError: Could not find a suitable TLS CA certificate bundle, invalid path: C:\Users\user\AppData\Local\Temp\_MEI253762\facebookads\fb_ca_chain_bundle.crt

我试图通过使用此代码来解决此问题,但 MEI 文件夹在我每次运行此代码时都会更改其数字,所以它没有用。

dst = r'C:\Users\user\AppData\Local\Temp\_MEI120642\facebookads'
file = 'fb_ca_chain_bundle.crt'

try:
    os.makedirs(dst);  ## it creates the destination folder
except:
    pass

shutil.move(file, dst)

所以我去了这个文件

C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\site-packages\requests\adapters.py

并尝试对引发此错误但出现 SSL 错误的 if 语句进行注释。我找不到负责生成这些 MEI 数字的代码。

def cert_verify(self, conn, url, verify, cert):
    """Verify a SSL certificate. This method should not be called from user
    code, and is only exposed for use when subclassing the
    :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.

    :param conn: The urllib3 connection object associated with the cert.
    :param url: The requested URL.
    :param verify: Either a boolean, in which case it controls whether we verify
        the server's TLS certificate, or a string, in which case it must be a path
        to a CA bundle to use
    :param cert: The SSL certificate to verify.
    """
    if url.lower().startswith('https') and verify:

        cert_loc = None

        # Allow self-specified cert location.
        if verify is not True:
            cert_loc = verify

        if not cert_loc:
            cert_loc = DEFAULT_CA_BUNDLE_PATH

        if not cert_loc or not os.path.exists(cert_loc):
            raise IOError("Could not find a suitable TLS CA certificate bundle, "
                          "invalid path: 0".format(cert_loc))

        conn.cert_reqs = 'CERT_REQUIRED'

        if not os.path.isdir(cert_loc):
            conn.ca_certs = cert_loc
        else:
            conn.ca_cert_dir = cert_loc
    else:
        conn.cert_reqs = 'CERT_NONE'
        conn.ca_certs = None
        conn.ca_cert_dir = None

    if cert:
        if not isinstance(cert, basestring):
            conn.cert_file = cert[0]
            conn.key_file = cert[1]
        else:
            conn.cert_file = cert
            conn.key_file = None
        if conn.cert_file and not os.path.exists(conn.cert_file):
            raise IOError("Could not find the TLS certificate file, "
                          "invalid path: 0".format(conn.cert_file))
        if conn.key_file and not os.path.exists(conn.key_file):
            raise IOError("Could not find the TLS key file, "
                          "invalid path: 0".format(conn.key_file))

【问题讨论】:

我必须在 cert_verify() 函数的开头放置一个 return 语句。这非常肮脏和可怕,但它奏效了。 【参考方案1】:

我也遇到了这个问题。看起来它来自证书包cacert.pem,在编译程序时没有包含在requests 包目录中。 requests 模块使用函数certifi.core.where 来确定@​​987654325@ 的位置。覆盖这个函数并覆盖这个函数设置的变量似乎可以解决问题。

我将此代码添加到程序的开头:

import sys, os


def override_where():
    """ overrides certifi.core.where to return actual location of cacert.pem"""
    # change this to match the location of cacert.pem
    return os.path.abspath("cacert.pem")


# is the program compiled?
if hasattr(sys, "frozen"):
    import certifi.core

    os.environ["REQUESTS_CA_BUNDLE"] = override_where()
    certifi.core.where = override_where

    # delay importing until after where() has been replaced
    import requests.utils
    import requests.adapters
    # replace these variables in case these modules were
    # imported before we replaced certifi.core.where
    requests.utils.DEFAULT_CA_BUNDLE_PATH = override_where()
    requests.adapters.DEFAULT_CA_BUNDLE_PATH = override_where()

【讨论】:

我看过很多“解决方案”,但只有这个有效!谢谢..所有其他解决方案都误导了公司代理和证书.. 我遇到了同样的错误,但这个解决方案对我不起作用。有什么帮助吗? 我在数据块中遇到了同样的错误,但这个解决方案对我不起作用。有关如何解决此错误的任何建议。【参考方案2】:

这可能是requests 包的问题。

我通过手动将cacert.pem 文件从/lib/site-packages/certifi 复制到/lib/site-packages/requests 解决了这个问题

如果您想用.exe 解决此问题,请将cacert.pem 文件从/lib/site-packages/certifi 复制到dist/library.zip/certifi/

我认为您已经使用py2exe 创建了exe,其中py2exe 将在包含所有脚本依赖项的dist/ 下创建library.zip。我不知道其他exe 转换器是否创建library.zip

【讨论】:

如果构建的 exe 没有 library.zip 怎么办?【参考方案3】:

如果要禁用证书验证,可以使用requests.get()中的verify=False参数:

requests.get('https://example.com', verify=False)

【讨论】:

以上是关于python请求转换为.exe时找不到带有证书的文件夹的主要内容,如果未能解决你的问题,请参考以下文章

安装 gulp-converter-tjs 时找不到 Python 可执行文件

调用 lambda 函数时找不到模块

在终端中构建时找不到 .pkg 文件/如何将 .app 转换为 .pkg

visualstudio执行程序时找不到exe文件是怎么回事?

使用 Pyinstaller 时找不到隐藏的导入 Tensorflow 包

重新定义默认 SSL 上下文时找不到 Java 密钥库