间歇性获取SSLError:[Errno 8] _ssl.c:499:进行Google API调用时发生EOF违反协议错误

时间:2019-07-31 16:05:04

标签: python python-2.7 google-drive-api google-docs-api

我正在使用python对Google驱动器和Google Doc API进行一些调用。在大多数情况下,它可以按预期工作,但偶尔(可能是10%的时间),我看到此错误:“ SSLError:[Errno 8] _ssl.c:499:EOF违反协议发生”

运行以下代码时发生错误:

from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build

creds = ServiceAccountCredentials.from_json_keyfile_name(
    credentialsFilepath, scopes=credentialScopes)
docService = build("docs", "v1", credentials=creds, cache_discovery=False)

这是错误发生位置的更详细的堆栈跟踪:

SSLError: [Errno 8] _ssl.c:499: EOF occurred in violation of protocol

Data[Traceback]=file ssl.py, line 283, in do_handshake
file ssl.py, line 121, in __init__
file ssl.py, line 344, in wrap_socket
file ...\CustomLib\httplib2\__init__.py, line 104, in _ssl_wrap_socket
file ...\CustomLib\httplib2\__init__.py, line 1414, in connect
file ...\CustomLib\httplib2\__init__.py, line 1711, in _conn_request
file ...\CustomLib\httplib2\__init__.py, line 1797, in _request
file ...\CustomLib\httplib2\__init__.py, line 2172, in request
file ...\CustomLib\googleapiclient\discovery.py, line 274, in _retrieve_discovery_doc
file ...\googleapiclient\discovery.py, line 232, in build
file ...\googleapiclient\_helpers.py, line 130, in positional_wrapper
file <....GoogleAPITest>, line 31, in buildDocService 

基于一些我在网上看到的类似问题,人们说要确保使用正确的ssl_version。因此,我尝试修补httplib2库的_ssl_wrap_socket函数以强制ssl_version = ssl.PROTOCOL_TLSv1。这是修补的函数:

def _ssl_wrap_socket(
    sock, key_file, cert_file, disable_validation, ca_certs, ssl_version, hostname
):
    if disable_validation:
        cert_reqs = ssl.CERT_NONE
    else:
        cert_reqs = ssl.CERT_REQUIRED

    ssl_version = ssl.PROTOCOL_TLSv1

    if hasattr(ssl, "SSLContext"):  # Python 2.7.9
        context = ssl.SSLContext(ssl_version)
        context.verify_mode = cert_reqs
        context.check_hostname = cert_reqs != ssl.CERT_NONE
        if cert_file:
            context.load_cert_chain(cert_file, key_file)
        if ca_certs:
            context.load_verify_locations(ca_certs)
        return context.wrap_socket(sock, server_hostname=hostname)
    else:
        return ssl.wrap_socket(
            sock,
            keyfile=key_file,
            certfile=cert_file,
            cert_reqs=cert_reqs,
            ca_certs=ca_certs,
            ssl_version=ssl_version,
        )

不幸的是,它似乎无法解决此问题,因为我仍然偶尔会看到该错误。这只是间歇性发生,这似乎很奇怪。任何帮助将不胜感激。

0 个答案:

没有答案