【问题标题】:How to move a file in a shared google drive to trash using a service account如何使用服务帐户将共享谷歌驱动器中的文件移动到垃圾箱
【发布时间】:2020-10-21 07:55:36
【问题描述】:

我使用的是内容管理器服务帐户。我使用 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:找不到文件。

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

【问题讨论】:

  • 您使用的是哪个 Drive API 版本?
  • @JoseVasquez 我正在使用 Drive api v3

标签: python google-api google-drive-api google-api-python-client shared-drive


【解决方案1】:

要求

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

解决方案

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 2015-01-23
    • 2013-04-07
    • 2011-10-10
    相关资源
    最近更新 更多