gpt4 book ai didi

Python Google Drive API - 获取我的云端硬盘文件夹的 ID

转载 作者:行者123 更新时间:2023-12-05 08:51:30 55 4
gpt4 key购买 nike

在 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

然后我可以迭代结果以找到名称为“My Drive”的文件夹,但是,坦率地说,获取文件夹列表花费的时间太长了(有问题的用户在 Team Drives 上创建了大量文件夹从我们将本地共享驱动器迁移到 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,并在驱动器的根目录上创建一个名为“Root Folder”的文件夹,然后在上面的函数中使用此查询搜索它:

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?

最佳答案

目前正在使用 API v3:

driveid = service.files().get(fileId='root').execute()['id']

关于Python Google Drive API - 获取我的云端硬盘文件夹的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59756951/

55 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com