Python调用Google Analytics API遇503 SSL证书验证失败求助
问题描述
我开发了通过Google Analytics API获取报告的Python脚本,使用的库如下:
from google.analytics.data import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import DateRange, Dimension, Metric, RunReportRequest, Filter, FilterExpression from google.oauth2 import service_account
运行代码时出现如下错误:
Traceback (most recent call last): File "H:\\PythonProjects\\GoogleAnalytics\\Venv_GoogleAnalytics\\lib\\site-packages\\google\\api_core\\grpc_helpers.py", line 76, in error_remapped_callable return callable_(*args, **kwargs) File "H:\\PythonProjects\\GoogleAnalytics\\Venv_GoogleAnalytics\\lib\\site-packages\\grpc\\_channel.py", line 1181, in __call__ return _end_unary_response_blocking(state, call, False, None) File "H:\\PythonProjects\\GoogleAnalytics\\Venv_GoogleAnalytics\\lib\\site-packages\\grpc\\_channel.py", line 1006, in _end_unary_response_blocking raise _InactiveRpcError(state) # pytype: disable=not-instantiable grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with: status = StatusCode.UNAVAILABLE details = "failed to connect to all addresses; last error: UNKNOWN: ipv4:: Ssl handshake failed (TSI_PROTOCOL_FAILURE): SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED" debug_error_string = "UNKNOWN:Error received from peer {grpc_message:\"failed to connect to all addresses; last error: UNKNOWN: ipv4:: Ssl handshake failed (TSI_PROTOCOL_FAILURE): SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED\", grpc_status:14, created_time:\"2024-10-14T12:52:05.1830382+00:00\"}" > The above exception was the direct cause of the following exception: Traceback (most recent call last): File "H:\\PythonProjects\\GoogleAnalytics\\GAPYTHON\\deneme.py", line 106, in <module> main() File "H:\\PythonProjects\\GoogleAnalytics\\GAPYTHON\\deneme.py", line 97, in main response = get_report(analytics) File "H:\\PythonProjects\\GoogleAnalytics\\GAPYTHON\\deneme.py", line 48, in get_report response = analytics.run_report(request) File "H:\\PythonProjects\\GoogleAnalytics\\Venv_GoogleAnalytics\\lib\\site-packages\\google\\analytics\\data_v1beta\\services\\beta_analytics_data\\client.py", line 784, in run_report response = rpc( File "H:\\PythonProjects\\GoogleAnalytics\\Venv_GoogleAnalytics\\lib\\site-packages\\google\\api_core\\gapic_v1\\method.py", line 131, in __call__ return wrapped_func(*args, **kwargs) File "H:\\PythonProjects\\GoogleAnalytics\\Venv_GoogleAnalytics\\lib\\site-packages\\google\\api_core\\timeout.py", line 120, in func_with_timeout return func(*args, **kwargs) File "H:\\PythonProjects\\GoogleAnalytics\\Venv_GoogleAnalytics\\lib\\site-packages\\google\\api_core\\grpc_helpers.py", line 78, in error_remapped_callable raise exceptions.from_grpc_error(exc) from exc google.api_core.exceptions.ServiceUnavailable: 503 failed to connect to all addresses; last error: UNKNOWN: ipv4: Ssl handshake failed (TSI_PROTOCOL_FAILURE): SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED
已检查防火墙和代理设置,未发现问题,且更新了证书库,请问该如何解决此问题?
解决方案
针对SSL证书验证失败的问题,可尝试以下几种方法:
1. 切换到REST传输模式
Google Analytics Data API客户端默认使用gRPC,其SSL证书处理逻辑可能引发兼容性问题。可通过强制使用REST传输规避该问题:
- 在Python脚本开头添加环境变量配置:
import os os.environ['GOOGLE_API_USE_REST_TRANSPORT'] = 'true' - 或在Windows命令行中先执行再运行脚本:
set GOOGLE_API_USE_REST_TRANSPORT=true
2. 手动指定SSL证书路径
如果gRPC无法自动识别系统根证书,可手动指定证书文件路径。推荐使用certifi库提供的标准证书:
import certifi import grpc from google.analytics.data import BetaAnalyticsDataClient from google.oauth2 import service_account # 获取certifi的证书路径 cert_path = certifi.where() with open(cert_path, 'rb') as f: ssl_credentials = grpc.ssl_channel_credentials(root_certificates=f.read()) # 初始化服务账号凭证 credentials = service_account.Credentials.from_service_account_file( 'path/to/your/service-account-key.json' ) # 结合两种凭证创建客户端 client = BetaAnalyticsDataClient( credentials=credentials, client_options={'grpc_channel_credentials': ssl_credentials} )
3. 更新相关依赖包
旧版本的gRPC或Google API客户端库可能存在SSL Bug,执行以下命令升级依赖:
pip install --upgrade grpcio google-api-core google-analytics-data certifi
4. 验证服务账号权限
确认你的服务账号JSON密钥文件有效,且已在GA4控制台中被授予数据查看者或更高权限,避免因权限问题间接引发连接异常。
内容的提问来源于stack exchange,提问作者Saturn
相关产品推荐
相关产品推荐

