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

使用Python下载Google Play控制台报表遇ServiceAccountCredentials报错求助

问题排查与解决方案

核心错误原因

  • 你使用的oauth2client.service_account.ServiceAccountCredentials属于已废弃的库组件,和你当前安装的google-auth 2.3.3版本适配存在问题,传参逻辑不符合官方最新的认证规范
  • Google Cloud Storage的objects.get接口不支持直接传入带通配符*的对象路径,必须先列举存储桶下的对象,再按文件名规则筛选目标文件
  • 你当前的代码调用execute()仅能获取文件元数据,无法下载实际的报表压缩包内容

修正后可运行代码

import json
import os
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload

# 配置参数
JSON_KEY_PATH = os.path.join(os.path.dirname(__file__), 'private_key.json')
CLOUD_STORAGE_BUCKET = 'pubsite_prod_rev_***********'
# 去掉通配符,只保留前缀用于匹配
REPORT_PREFIX = 'earnings/earnings_201811_'
SCOPES = ['https://www.googleapis.com/auth/devstorage.read_only']

# 初始化认证(直接加载完整密钥文件,避免单独提取字段出错)
credentials = service_account.Credentials.from_service_account_file(
    JSON_KEY_PATH,
    scopes=SCOPES
)

# 构建GCS服务客户端
storage = build('storage', 'v1', credentials=credentials)

# 第一步:列举存储桶下匹配前缀的对象
response = storage.objects().list(
    bucket=CLOUD_STORAGE_BUCKET,
    prefix=REPORT_PREFIX
).execute()

if not response.get('items', []):
    print("未找到匹配的报表文件")
else:
    # 取第一个匹配的文件,如有多个可以自行筛选
    target_object = response['items'][0]['name']
    print(f"找到目标文件:{target_object}")
    
    # 第二步:下载文件到本地
    request = storage.objects().get_media(
        bucket=CLOUD_STORAGE_BUCKET,
        object=target_object
    )
    
    # 本地保存路径
    save_path = os.path.join(os.path.dirname(__file__), target_object.split('/')[-1])
    with open(save_path, 'wb') as f:
        downloader = MediaIoBaseDownload(f, request)
        done = False
        while not done:
            status, done = downloader.next_chunk()
            print(f"下载进度:{int(status.progress() * 100)}%")
    
    print(f"文件已保存到:{save_path}")

额外注意事项

  • 无需单独提取密钥文件中的client_email和private_key字段,直接加载完整密钥文件的方式可以最大程度避免传参错误
  • 确认你的服务账号已经在Google Play控制台的用户与权限页面,被授予了财务信息查看权限,对应存储桶的访问权限配置正确
  • 如果只需要获取文件元数据,不需要下载内容,可以直接调用storage.objects().get(bucket=CLOUD_STORAGE_BUCKET, object=target_object).execute()获取对应信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 00:27:03