You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python调用GA4的properties.getDataRetentionSettings接口?

如何用Python调用GA4的properties.getDataRetentionSettings接口

1. 安装依赖库

首先需要安装Google Analytics Admin的Python客户端库,执行以下命令:

pip install google-analytics-admin

2. 认证配置

和你之前使用的GA4数据查询接口逻辑一致,需通过服务账号或OAuth完成身份认证:

  • 使用服务账号时,设置环境变量指向你的密钥文件:
    export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account-key.json"
    
  • 本地调试时也可直接在代码中指定密钥文件路径。

3. 编写调用代码

替换你的GA4媒体资源ID即可运行以下完整示例:

from google.analytics.admin import AnalyticsAdminServiceClient

def fetch_data_retention_settings(property_id):
    # 初始化Admin服务客户端
    client = AnalyticsAdminServiceClient()
    # 构造媒体资源的完整资源名称,格式为 properties/{property_id}
    property_resource = f"properties/{property_id}"
    # 调用getDataRetentionSettings接口
    retention_settings = client.get_data_retention_settings(property=property_resource)
    
    # 解析并输出核心配置项
    print(f"事件数据保留时长: {retention_settings.event_data_retention_duration}")
    print(f"新活动触发时重置用户数据: {retention_settings.reset_user_data_on_new_activity}")
    print(f"用户数据保留时长: {retention_settings.user_data_retention_duration}")

if __name__ == "__main__":
    # 替换为你的GA4媒体资源ID
    YOUR_GA4_PROPERTY_ID = "123456789"
    fetch_data_retention_settings(YOUR_GA4_PROPERTY_ID)

关键说明

  • 资源名称必须严格遵循properties/{property_id}格式,不能直接传入纯数字ID;
  • 返回的retention_settings对象包含所有数据保留配置字段,可根据需求提取更多内容;
  • 认证账号需拥有该GA4媒体资源的管理员权限,否则会返回权限错误。

内容的提问来源于stack exchange,提问作者leleos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 19:32:41