Reputation: 4929
I'm trying to query a list of the first 10 files from my Google Drive. Along with the files I want to get the directory it resides in...
There has got to be a better way to do what I'm after. Currently I call FindFiles()
and that function calls GetDriveObjectParentPath()
to get the parents path of each file. Because of the loop in GetDriveObjectParentPath()
when it calls itself I run into a User Rate Limit Exceeded [403]
error!
Can someone show me a better way to do what I'm after with a full example please?
private string GetDriveObjectParentPath(DriveService drive, string objectId, bool digging = false)
{
string parentPath = "";
FilesResource.GetRequest request = drive.Files.Get(objectId);
request.Fields = "id, name, parents";
Google.Apis.Drive.v3.Data.File driveObject = request.Execute();
if (digging)
parentPath += "/" + driveObject.Name;
if (driveObject.Parents != null)
parentPath = GetDriveObjectParentPath(drive, driveObject.Parents[0], true) + parentPath;
return parentPath;
}
private bool FindFiles()
{
//Setup the API drive service
DriveService drive = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = m_credentials,
ApplicationName = System.AppDomain.CurrentDomain.FriendlyName,
});
//Setup the parameters of the request
FilesResource.ListRequest request = drive.Files.List();
request.PageSize = 10;
request.Fields = "nextPageToken, files(mimeType, id, name, parents)";
//List first 10 files
IList<Google.Apis.Drive.v3.Data.File> files = request.Execute().Files;
if (files != null && files.Count > 0)
{
foreach (Google.Apis.Drive.v3.Data.File file in files)
{
Console.WriteLine("{0} ({1})", file.Name, file.Id);
string parentPath = GetDriveObjectParentPath(drive, file.Id);
Console.WriteLine("Found file '" + file.Name + "' that is in directory '" + parentPath + "' and has an id of '" + file.Id + "'.");
}
}
else
{
Console.WriteLine("No files found.");
}
Console.WriteLine("Op completed.");
return true;
}
Using the above produces the following API usage for one single run and results in the 403 client error...
Upvotes: 0
Views: 2235
Reputation: 22286
Your code is fine as is. you just need to deal with the 403 Rate Limit by doing things more slowly and retrying. I know it sucks, but that's just how Drive works.
I normally see 403 rate Limit errors after 30 or so requests, so that fits in with your observation.
In terms of approach, whenever I see a question that contains "folder hierarchy", my advice is always the same. Start by fetching ALL folders using a files.list q:mimetype='application/vnd.google-apps.folder'. Then process that list once to build up an in-memory hierarchy. Then go fetch your files and locate them in the hierarchy. Always remember that in GDrive, the "hierarchy" is somewhat imaginary since parents are simply properties of any given file/folder. This means that a file/folder can have multiple parents, and also that the hierarchy can even loop back on itself.
Upvotes: 1