python 由于 Windows 上的信任库为空,treq 失败并出现 Twisted/OpenSSL 错误

python treq fails with Twisted/OpenSSL error due to empty trust store on Windows

当我 运行 http://www.google.com 上的以下示例代码时,它工作正常 但是当我尝试 https://www.google.com 时,我得到这个错误:

Requesting https://www.google.com

Unhandled error in Deferred:
Unhandled Error
Traceback (most recent call last):
Failure: twisted.web._newclient.ResponseNeverReceived: [<twisted.python.failure.Failure <class 'OpenSSL.SSL.Error'>>]

我正在使用 python 2.7.8,扭曲的 14.0.2,service_identity 14.0.0,treq 0.2.1,OpenSSL 0.14

import treq
from twisted.internet import reactor, defer
import sys

@defer.inlineCallbacks
def doit(url):
    print "Requesting "+ url + "\n"
    results = yield treq.get(url)
    print "...got results\n"
    content = yield results.content()
    print "%s"%content
    reactor.stop()

def main():
    url = sys.argv[1]
    reactor.callLater(0, doit, url)
    reactor.run()

if __name__ == '__main__':
    main()

提前致谢!

这里的问题很可能是您没有选择任何信任根,因此 OpenSSL 无法验证连接。

您可以通过执行 pip install certifi 以 OpenSSL 可以使用的格式获得一些信任根,然后将您的 SSL_CERT_FILE 环境变量设置为指向 python -m certifi 的输出。在 Python 中,您可以在脚本的最顶部使用 import certifi; os.environ["SSL_CERT_FILE"] = certifi.where() 执行此操作(在导入任何 OpenSSL 绑定之前)。