You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用Python服务账号从Google Drive下载文件时遭遇AttributeError错误求助

使用Python服务账号从Google Drive下载文件时遭遇AttributeError错误求助

看起来你的问题出在服务账号凭证的加载方式上,我来帮你快速定位并解决:

错误原因分析

你代码里的这一行是问题根源:

credz = {"credentials.json"} #json credentials here from service account

{"credentials.json"} 这种写法创建的是一个Python集合(set),而service_account.Credentials.from_service_account_info()方法需要的是解析后的JSON字典(也就是把credentials.json里的内容转成Python字典格式)。集合没有keys()方法,所以Google的认证库在尝试处理时就抛出了AttributeError


两种修复方案(选一种即可)

方案1:直接用文件路径加载凭证(推荐,更简洁)

不需要手动读取JSON,Google的库提供了专门读取凭证文件的方法,把凭证加载的代码改成这样:

from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from google.oauth2 import service_account
import io

# 直接从JSON文件加载凭证,方法会自动解析内容
credentials = service_account.Credentials.from_service_account_file('credentials.json')
drive_service = build('drive', 'v3', credentials=credentials)

# 后面的下载逻辑保持不变
file_id = 'file_ID'
request = drive_service.files().get_media(fileId=file_id)
fh = io.FileIO('file.tar.gz', 'wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print("Download %d%%." % int(status.progress() * 100))

方案2:手动加载JSON为字典(适合需要先修改凭证内容的场景)

如果你确实需要先处理JSON内容,就先把文件读取成字典再传入:

from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from google.oauth2 import service_account
import io
import json # 记得导入json模块

# 读取JSON文件并解析为Python字典
with open('credentials.json', 'r') as f:
    credz = json.load(f)

credentials = service_account.Credentials.from_service_account_info(credz)
drive_service = build('drive', 'v3', credentials=credentials)

# 后续下载代码保持不变...

额外验证点

修复完凭证问题后,记得确认服务账号已经被授权访问目标文件

  1. 打开你的credentials.json,找到client_email字段对应的邮箱地址
  2. 把Google Drive上的目标文件共享给这个邮箱(权限至少设为“查看者”)

这样应该就能顺利完成下载了!

备注:内容来源于stack exchange,提问作者MBT_Py

火山引擎 最新活动