【发布时间】:2021-02-17 00:15:02
【问题描述】:
我有一个脚本可以使用 OAuth 客户端从 GDrive 文件中导出文本,效果很好 -
import googleapiclient.discovery as google
from apiclient.http import MediaIoBaseDownload
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import datetime, io, os, pickle
Scopes=" ".join(['https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/drive.metadata',
'https://www.googleapis.com/auth/drive.readonly'])
TokenFile="token.pickle"
def init_creds(clientfile,
scopes,
tokenfile=TokenFile):
token=None
if os.path.exists(tokenfile):
with open(tokenfile, 'rb') as f:
token=pickle.load(f)
if (not token or
not token.valid or
token.expiry < datetime.datetime.utcnow()):
if (token and
token.expired and
token.refresh_token):
token.refresh(Request())
else:
flow=InstalledAppFlow.from_client_secrets_file(clientfile, scopes)
token=flow.run_local_server(port=0)
with open(tokenfile, 'wb') as f:
pickle.dump(token, f)
return token
def export_text(id,
clientfile,
scopes=Scopes):
creds=init_creds(clientfile=clientfile,
scopes=scopes)
service=google.build('drive', 'v3', credentials=creds)
request=service.files().export_media(fileId=id,
mimeType='text/plain')
buf=io.BytesIO()
downloader, done = MediaIoBaseDownload(buf, request), False
while done is False:
status, done = downloader.next_chunk()
destfilename="tmp/%s.txt" % id
return buf.getvalue().decode("utf-8")
if __name__=='__main__':
print (export_text(id="#{redacted}"
clientfile="/path/to/oath/client.json"))
但是每次都必须通过 OAuth 流程很痛苦,因为只有我使用脚本,所以我想简化事情并改用服务帐户,从这篇文章开始 -
Google Drive API Python Service Account Example
我的新服务帐户脚本,做的一模一样,如下 -
import googleapiclient.discovery as google
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.http import MediaIoBaseDownload
import io
Scopes=" ".join(['https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/drive.metadata',
'https://www.googleapis.com/auth/drive.readonly'])
def export_text(id,
clientfile,
scopes=Scopes):
creds=ServiceAccountCredentials.from_json_keyfile_name(clientfile,
scopes)
service=google.build('drive', 'v3', credentials=creds)
request=service.files().export_media(fileId=id,
mimeType='text/plain')
buf=io.BytesIO()
downloader, done = MediaIoBaseDownload(buf, request), False
while done is False:
status, done = downloader.next_chunk()
destfilename="tmp/%s.txt" % id
return buf.getvalue().decode("utf-8")
if __name__=='__main__':
print (export_text(id="#{redacted}",
clientfile="path/to/service/account.json"))
但是当我为相同的 id 运行它时,我得到以下信息 -
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://www.googleapis.com/drive/v3/files/#{redacted}/export?mimeType=text%2Fplain&alt=media returned "File not found: #{redacted}.">
感觉就像服务帐户脚本正在通过身份验证步骤(即服务帐户凭据没问题),但在尝试获取文件时失败 - 很奇怪,因为我可以使用 OAuth 版本很好地获取它:/
鉴于 OAuth 客户端版本显然适用于相同的 id,对于可能导致服务帐户版本中出现此 404 错误的任何想法?
【问题讨论】:
-
问题: 1. 您是否拥有该文件? 2.您是否与服务帐户共享文件? 3. 您是在使用@gmail 还是在 Google Workspace 域中? 4. 如果您在域中,是否设置了域范围的委派?
-
1) 是 2) 否 - 您如何执行该步骤?认为这可能是问题 3) gmail 4) 否 5) 谢谢你
-
您使用通常共享文件的方法与服务帐户共享文件 - 只有您必须与服务帐户的电子邮件地址共享文件。格式为
service-account-name@project-id.iam.gserviceaccount.com
标签: python google-api google-drive-api google-api-python-client service-accounts