Google Drive API:检查文件夹是否存在

时间:2019-06-07 14:33:38

标签: python google-drive-api

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

具体:

  • 驱动器API的V3版本
  • Python客户端:googleapiclient

示例:

鉴于随附的驱动器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'}]

因此答案是肯定的,该文件夹存在。但是应该通过传递driveId来更有效地进行via .list()。那怎么办?我尝试了各种组合,所有这些组合似乎都引发了非200的响应。

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

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

1 个答案:

答案 0 :(得分:3)

使用mymoduledriveId时,您需要再提供两个参数:corpora="drive"includeItemsFromAllDrives

代码:

supportsAllDrives

更新

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

如果仍然遇到这些问题,则可以使用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 参数为您提供替代解决方案:

spaces