首页 > 解决方案 > Google Drive API:检查文件夹是否存在

问题描述

我正在使用 Google Drive API 试图回答一个看似简单的问题:驱动器中是否存在某个名称的文件夹?

规格:

例子:

给定封闭的驱动器 ID abcdef,名称June 2019(和 mimeType application/vnd.google-apps.folder)的文件夹是否存在?

目前路线:

>>> from googleapiclient.discovery import build
>>> # ... build credentials
>>> driveservice = build("drive", "v3", credentials=cred).files()
>>> [i for i in driveservice.list().execute()['files'] if 
...  i['name'] == 'June 2019' and i['mimeType'] == 'application/vnd.google-apps.folder']                                                                                                                                                                     
[{'kind': 'drive#file',
  'id': '1P1k5c2...........',
  'name': 'June 2019',
  'mimeType': 'application/vnd.google-apps.folder'}]

所以答案是肯定的,文件夹存在。但是应该有一种更有效的方法来通过.list()传递driveId. 怎么可能呢?我尝试了各种组合,所有这些组合似乎都会引发非 200 响应。

>>> FOLDER_ID = "abcdef........"
>>> driveservice.list(corpora="drive", driveId=FOLDER_ID).execute()                                                                                                                                                                                                          
# 403 response, even when adding the additional requested params

如何使用q参数按文件夹名称查询?

标签: pythongoogle-drive-api

解决方案


使用driveIdandcorpora="drive"时,需要多提供两个参数:includeItemsFromAllDrivesandsupportsAllDrives

代码:

response = driveservice.list(
    q="name='June 2019' and mimeType='application/vnd.google-apps.folder'",
    driveId='abcdef',
    corpora='drive',
    includeItemsFromAllDrives=True,
    supportsAllDrives=True
).execute()

for item in response.get('files', []):
    # process found item

更新:

如果它是您确定存在的驱动器 ID,并且您不断收到“找不到共享驱动器”错误,则可能是您为 api 获取的凭据的范围问题。此外,根据这些 Google API 文档,似乎发生了很多更改和弃用,所有这些都与共享驱动器 API 支持有关。 https://developers.google.com/drive/api/v3/enable-shareddrives https://developers.google.com/drive/api/v3/reference/files/list

如果您仍然遇到这些问题,请使用以下spaces参数为您提供替代解决方案:

response = driveservice.list(
    q="name='June 2019' and mimeType='application/vnd.google-apps.folder'",
    spaces='drive'
).execute()

for item in response.get('files', []):
    # process matched item

推荐阅读