Reputation: 89
I am currently working to a small program that can take a file/folder path in Google Drive (Ex: 'MyDrive/Folder1/Folder2/Folder3'), and do some operations on it (list, upload, download, copy, etc.)
The folder path is a string input by user (one user, aka me).
As specified by Google Drive API, most operations require a file/folder ID, so given user's file path, I need to figure out the file/folder ID. What I want is an efficient way to find the file/folderID. Note: in Google Drive, each file has 1 ID (string), and 1 title (ex: 'folder3', 'folder1'). IDs are unique. Each file also has a list of its parents'ID.
Since calling the Google Drive API takes a lot of time, I am trying to limit the number of API calls.
Right now, before I take user input, (1) I calls service.files().list(), which return a list of all files in my Google Drive. (2) Loop through the list to construct 3 dictionaries: FileName-FileID, FileID-FileName, FileID-Parents.
Given User input: 'MyDrive/Folder1/Folder2', I can: (1) Look up 'Folder2''s ID, then its parents'ID. (2) Look up 'Folder1''s ID, then its parents'ID. Check that "Folder1"'s ID is in 'Folder2''s ParentsID. (3) Look up 'MyDrive''s ID. Check that MyDrive's ID is in 'Folder1''s ID.
After checking, I can ensure that 'Folder2''s ID is the ID that I am trying to find out.
My questions: 1, Can you suggest a better way to find the ID in my case?
2, Right now, I think I may trust User's input, and only look up Folder2's ID. If Folder2 has more than 1 parents, then I will do the above process (Traverse through the path). If Folder2 has 1 parent, I stop checking. Is this too much trust in user?
I am rather new to programming, can you help me? Thank you for your time and your help!
Upvotes: 3
Views: 2899
Reputation: 2106
Here's a good starting place:
path = 'sample_folder'
folder_query = "title = '%s' and mimeType = '%s'" % (path,
"application/vnd.google-apps.folder")
folder_list = drive_service.files().list(q=folder_query).execute()
folder_id = folder_list['items'][0]['id']
#(note: this just returns the first search result)
If you have multiple folders in your path, you will need split the path and iterate through (eg. get the folder_id of Folder1, and then use this id to get the folder_id of Folder2, etc)
Upvotes: 2
Reputation: 2998
I'm not sure if its the best, but you can try to split the folder paths ("myFolder/folder1/folder2/...") and get the last item's File resource. The resource file will have a parents[]
value (though I don't know if it will contains parents of its folder as well leading to My Drive root).
Another thing to consider is for you to optimize the response to have a faster and concise result that you can do with your current implementation.
Try to optimize the files.list
by adding filters (you can specify that you only intend to list folders). Another item would be for you to have partial responses. This can be done by specifying the fields
parameter.
Hope this helps!
Upvotes: 1