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'}]
所以答案是肯定的,文件夹存在。但是应该有一种更有效的方法来通过.list()
传递driveId
. 怎么可能呢?我尝试了各种组合,所有这些组合似乎都会引发非 200 响应。
>>> FOLDER_ID = "abcdef........"
>>> driveservice.list(corpora="drive", driveId=FOLDER_ID).execute()
# 403 response, even when adding the additional requested params
如何使用q
参数按文件夹名称查询?
解决方案
使用driveId
andcorpora="drive"
时,需要多提供两个参数:includeItemsFromAllDrives
andsupportsAllDrives
代码:
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
推荐阅读
- excel - 比较 VBA 中的两个数字
- spring-boot - 带有 apache 磁贴的 Spring Boot 导致错误 org.apache.jasper.JasperException:无法为 JSP 编译类
- ios - 应该使用哪个 Designpattern 在 TabBarController 的选项卡之间共享短期数据
- c# - 跨度 - 访问原始值
- asp.net - 在 ASP.NET MVC 中使用视图特定的连接字符串
- oracle - oracle sql developer运行存储过程失败如何解决?
- ios - 如何根据后者的进度为已经运行的动画添加动画?
- laravel - Laravel paginate 在某些查询中不起作用,但在其他查询中起作用
- scala - Scala 泛型的模式匹配
- java - CriteriaBuilder 谓词 IN