适配Universal Analytics API的Google云客户端Python库是哪一个?
适配UA Analytics Reporting API v4的轻量化解决方案
Google Cloud Client Libraries确实没有针对Universal Analytics(UA)的官方客户端库——因为UA已经停止新数据收集,官方资源优先投向GA4相关工具。不过有两种轻量化方案可以满足AWS Lambda的空间需求:
方案1:精简使用google-api-python-client
原版库体积大是因为默认加载了所有Google API的发现文档,我们可以通过配置减少不必要的资源加载:
from google.oauth2 import service_account from googleapiclient.discovery import build def initialize_analyticsreporting(): SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] KEY_FILE_LOCATION = 'service-account-key.json' credentials = service_account.Credentials.from_service_account_file( KEY_FILE_LOCATION, scopes=SCOPES) # 仅加载UA Reporting v4的发现文档,禁用缓存减少打包体积 analytics = build( 'analyticsreporting', 'v4', credentials=credentials, cache_discovery=False ) return analytics
打包Lambda时,还可以通过排除google-api-python-client中无关的API模块,或者使用Lambda层复用依赖,进一步压缩包体积。
方案2:直接调用REST API(最轻量化)
完全绕过客户端库,用requests直接发送HTTP请求,依赖极少,体积最小:
import requests from google.oauth2 import service_account def get_ua_report(): SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] KEY_FILE_LOCATION = 'service-account-key.json' VIEW_ID = 'ga:XXXXXXX' # 替换为你的UA视图ID # 获取服务账号访问令牌 credentials = service_account.Credentials.from_service_account_file( KEY_FILE_LOCATION, scopes=SCOPES) token = credentials.token # 构造API请求 url = 'https://analyticsreporting.googleapis.com/v4/reports:batchGet' headers = { 'Authorization': f'Bearer {token}', 'Content-Type': 'application/json' } payload = { 'reportRequests': [ { 'viewId': VIEW_ID, 'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}], 'metrics': [{'expression': 'ga:sessions'}], 'dimensions': [{'name': 'ga:date'}] } ] } # 发送请求并返回结果 response = requests.post(url, json=payload, headers=headers) if response.status_code == 200: return response.json() else: raise Exception(f"API请求失败: {response.text}")
这种方式只需要requests和google-auth两个核心依赖,打包后的体积远小于完整的客户端库,完美适配Lambda的空间限制。
内容的提问来源于stack exchange,提问作者Simon Cook
相关产品推荐
相关产品推荐

