在 Python 3 中使用 Drive API。我正在尝试编写一个脚本来下载整个用户的 Google Drive。
此代码来自 Drive API V3 文档,经过修改以搜索文件夹而不是文件,将获取用户拥有所有权的每个文件夹,包括团队驱动器上的文件夹 - 尽管 files().list 的 API 文档说它没有2020 年 6 月 1 日之前不会
def GetFolderListFromGoogle(GDrive):
page_token = None
while True:
response = GDrive.files().list(q="mimeType='application/vnd.google-apps.folder' and 'me' in owners and trashed = false",spaces='drive',fields='nextPageToken, files(id, name, mimeType, parents, sharingUser)',pageToken=page_token).execute()
for file in response.get('files', []):
# Process change
print('Found file: %s with id %s of type %s with parent %s and shared by is %s' % (file.get('name'), file.get('id'),file.get('mimeType'),file.get('parents'), file.get('sharingUser.displayName')))
page_token = response.get('nextPageToken', None)
if page_token is None:
break
print(response)
return response
然后,我可以迭代结果以找到名为“我的云端硬盘”的文件夹,但是,坦率地说,仅获取文件夹列表就花费了太长的时间(有问题的用户从我们开始在团队云端硬盘上创建了大量文件夹)将我们的本地共享驱动器迁移到 Google)。
因此,为了解决这个问题,我尝试这样做:
def GetMyDriveFolderIDFromGoogle(GDrive):
page_token = None
while True:
response = GDrive.files().list(q="name = 'My Drive'",spaces='drive',fields='nextPageToken, files(id, name, mimeType, parents, sharingUser)',pageToken=page_token).execute()
for file in response.get('files', []):
# Process change
print('Found file: %s with id %s' % (file.get('name'), file.get('id')))
parent = file.get('parents')
if parent:
while True:
folder = GDrive.files().get(fileId=parent[0], fields='id, name, parents').execute()
print("ID: "+parent[0]+ " name: "+folder.get('name'))
parent = folder.get('parents')
if parent is None:
break
page_token = response.get('nextPageToken', None)
if page_token is None:
break
break
print(response)
return response
除此之外,它什么也不返回。如果我然后进入我的测试帐户的 Google Drive,并在驱动器的根目录上创建一个名为“根文件夹”的文件夹,然后使用上面函数中的此查询来搜索它:
response = GDrive.files().list(q="mimeType='application/vnd.google-apps.folder' and name = 'Root Folder' and trashed = false",spaces='drive',fields='nextPageToken, files(id, name, mimeType, parents, sharingUser)',pageToken=page_token).execute()
当我查询我创建的“根文件夹”的父级时,它返回以下内容:
Found file: Root Folder with id <ID OF TEST FOLDER HERE> of type application/vnd.google-apps.folder with parent ['<ID OF MY DRIVE FOLDER HERE>'] and shared by is None
ID: <ID OF MY DRIVE FOLDER HERE> name: My Drive
那么Drive API知道My Drive文件夹存在,它被命名为“My Drive”,有一个ID,并且可以获取它的ID,但只是不允许您直接访问它?
由于我无法保证每个用户都有任何文件夹,是否有更好的方法来获取“我的云端硬盘”文件夹的 ID?