我正在使用Google drive API试图回答一个看似简单的问题:驱动器中是否存在某个名称的文件夹?
具体内容:
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
参数按文件夹名称查询?
发布于 2019-06-10 19:22:16
使用driveId
和corpora="drive"
时,还需要提供两个参数:includeItemsFromAllDrives
和supportsAllDrives
代码:
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
https://stackoverflow.com/questions/56496333
复制