简体   繁体   中英

Python Google Drive API - Get the ID of the My Drive folder

Working with the Drive API in Python 3. I'm trying to write a script which will download an entire user's Google Drive.

This code, from the Drive API V3 docs, modified to search for folders instead of files, will get EVERY folder the user has ownership of, including folders on team drives - despite the fact the API documentation for files().list saying it doesn't / won't until June 1, 2020

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

I could then iterate the results to find the folder with the name "My Drive", however, it quite frankly takes WAY too long just to get the folder list (the user in question created a metric ton of folders on Team Drives from when we migrated our on prem shared drives to Google).

So, in an attempt to get around that issue, I tried to do this:

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

Except, it returns nothing. If I then go into Google Drive of my test account, and create a folder called "Root Folder" right on the root of the drive and then search for it using this query in the function above:

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()

It returns the following when I query the parent of the "Root Folder" I created:

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

So the Drive API is aware that the My Drive folder exists, it is named "My Drive", has an ID, and can obtain it the ID but just won't let you access it directly?

Since there aren't any folders I can guarantee every user has, is there a better way to get the ID of the My Drive folder?

目前正在使用 API v3:

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

Arguably not the most elegant way, but if you want to get "My Drive" ID, why don't you create a folder in My Drive , find its parent id (that is, "My Drive" ID) and then delete that folder? For example, this:

file_metadata = {
    'name': 'temporary folder',
    'mimeType': 'application/vnd.google-apps.folder'
}
tempFolderId = GDrive.files().create(body=file_metadata, fields='id').execute()["id"] # Create temporary folder
myDriveId = GDrive.files().get(fileId=tempFolderId, fields='parents').execute()["parents"][0] # Get parent ID
GDrive.files().delete(fileId=tempFolderId).execute() # Delete temporary folder
return myDriveId

I hope this is of any help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM