要求
如果您清楚地了解如何模拟帐户,则可以跳到该Solution
步骤。
解决方案
默认情况下, Python Google Drive API 客户端 V3不包含共享驱动器文件,这就是为什么您必须显式传递一个参数supportsAllDrives
并将其设置为 True 并且在此之前您应该列出您的文件以便使用and知道fileId参数。以下示例列出了所有驱动器中的所有文件以及如何使用服务帐户将共享驱动器中的文件删除:includeItemsFromAllDrives
supportsAllDrives
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 客户端 V3 > 更新文件
Google Identity Platform > 使用服务帐户模拟用户