微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用服务帐户将共享Google驱动器中的文件移至垃圾箱

如何解决如何使用服务帐户将共享Google驱动器中的文件移至垃圾箱

我使用的是内容管理员的服务帐户。我使用python的drive-api将文件上传到共享驱动器没有问题。使用

service.files().list(q="name='file_name'",fields="files(id)").execute() 

我从我的代码中获得了file_id。根据文件链接,此file_id是正确的。

当我执行以下语句时:

response = service.files().update(fileId=file_id,body={'trashed': True}).execute()

我得到一个

404:找不到文件

该如何解决?使用我的个人帐户(也作为内容管理员),我可以毫无问题地删除文件

解决方法

要求

如果您清楚地了解如何模拟帐户,则可以跳至Solution步骤。

解决方案

默认情况下,Python Google Drive API client V3不包含共享驱动器文件,这就是为什么您必须显式传递参数supportsAllDrives并将其设置为True的原因,在此之前,您应该列出文件以了解使用includeItemsFromAllDrivessupportsAllDrives fileId 参数。下面是一个示例,列出所有驱动器中的所有文件以及如何使用服务帐户将文件删除到共享驱动器中:

from googleapiclient.discovery import build
from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = './service_account_key.json'

credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE,scopes=SCOPES)

# Impersonate user@example.com account in my example.com domain
delegated_credentials = credentials.with_subject('user@example.com')

# Use the delegated credentials to impersonate the user
service = build('drive','v3',credentials=delegated_credentials)

# List all the files in your Drives (Shared Drives included)
results = service.files().list(fields="nextPageToken,files(id,name,trashed)",includeItemsFromAllDrives=True,supportsAllDrives=True).execute()
items = results.get('files',[])

if not items:
    print('No files found.')
else:
    print('Files:')
    for item in items:
        print(u'{0} ({1}) - Trashed? {2}'.format(item['name'],item['id'],item['trashed']))

# Use the filedId in order to trash your shared file
response = service.files().update(fileId=fileId,body={'trashed': True},supportsAllDrives=True).execute()
print(response)

否则,如果您已经知道 fileId ,则只需使用update部分。

参考

Python Google Drive API client V3 > Update a file

Google Identity Platform > Impersonate a user by using a service account

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。