finds.utils.gdrive
Convenience class methods to use google drive apis
google REST api’s
#pip install google-api-python-client
Author: Terence Lim License: MIT
- class finds.utils.gdrive.GDrive(tokenfile='token.pkl')[source]
Bases:
object
Base class provides basic interface to essential google drive api’s
- Variables:
to_url (str formatter) – prepend to shared google drive file_id to construct url for download
Examples
# init() prompts for googleapi authorization, which is stored in a tokenfile # in current folder so that not prompted in subsequent executions g = GDrive()
_ = g.ls() # display list of folders and files (and types)
# NOTE: in all methods, set silent=True to turn off raise exceptions # and return None on error (letting caller handle errors gracefully) items = g.ls(silent=True) # returns files+folders and their fields
g.cd() # returns remote current working directory g.mkdir(‘/new_folder’) # create new folder with absolute path name g.cd(‘new_folder’) # change remote cwd g.mkdir(‘another_folder’) # create new folder in remote cwd g.put(‘local.txt’, ‘another_folder/newfile.txt’) # upload, relative path g.put(‘local.txt’, ‘/new_folder’) # upload, absolute path, infer filename g.put(‘local.txt’) # upload to remote cwd, infer filename g.get(‘/new_folder/local.txt’, ‘localfile.txt’) # upload, absolute path g.get(‘another_folder/newfile.txt’) # upload, relative path, infer filename g.rm(‘/new_folder/local.txt’) # remove, absolute path g.rm(‘another_folder/newfile.txt’) # remove, relative path g.rmdir(‘another_folder’) # remove folder from remote cwd g.rmdir(‘/new_folder’) # remove folder with absolute path name
Notes
See https://developers.google.com/drive/api/v3/quickstart/python to turn on the Drive API. In resulting dialog click DOWNLOAD CLIENT CONFIGURATION and save the file credentials.json to your working directory.
Initially, the class will attempt to open browser to prompt for authorization (information is stored in tokenfile, so subsequent executions will not prompt). If this fails, copy the URL from the console and manually open it in your browser.
Requirements
pip install –upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
- chmod(path, action='list', role='reader', email=None, silent=False)[source]
List, delete or create sharing permissions for a remote file
- Parameters:
path (str) – name of remote file to change permissions of
action (str in {'list' (default), 'create', 'delete'}) – permissions action to execute
role (str in {'reader' (default), 'writer', 'owner', 'commenter'}) – role to permit
- Returns:
result – number of permissions listed or deleted, or shareable link created
- Return type:
int or str
- fetchall(q="'root' in parents", filters={'ownedByMe': True, 'trashed': False}, fields=['id', 'name', 'parents', 'mimeType'], silent=True)[source]
Helper method to fetch list of all files
- Parameters:
q (str, default "'root' in parents" (select files in top-level folder)) – Search query string with which to call service.files().list()
filters (list of dict, default is {'ownedByMe': True, 'trashed':False}) – Files metadata properties to filter on, see https://developers.google.com/drive/api/v3/reference/files
fields (list of str, default is ['id','name','parents','mimeType']) – Specific fields of files to return, see https://developers.google.com/drive/api/v3/fields-parameter
- Returns:
result – dicts of specified fields for list of files that pass filter
- Return type:
list of dicts
Notes
- fetchone(path, field=None)[source]
Fetch metadata for one file given its path name
- Parameters:
path (str) – remote path name
field (str in {'id', 'name', 'mimeType', 'parents'}, default is None) – specific metadata field to return. None to return all fields
- Returns:
match – value or dict of metadata values of matched file. None if not found
- Return type:
value, or dict of values, or None
- get(path, filename='', silent=False)[source]
Download a remote file to local filename
- Parameters:
path (str) – relative or absolute path name of remote file
filename (str, default is '') – Output filename. If blank: infer basename, save in curr local dir
silent (bool, default False) – if True, print file statistics if successful, raise exception if not
- Returns:
total_file_size – or None if unsuccessful and silent
- Return type:
int
Notes
see https://developers.google.com/drive/api/v3/manage-downloads
- put(filename, path='', silent=False)[source]
Upload a local filename to remote folder file
- Parameters:
filename (str) – Input local filename
path (str, default is '') – Absolute or relative output filename or folder (basename inferred from local filename). If blank: upload to current remote folder
silent (bool, default False) – if False, print file statistics if successful
- Returns:
total_file_size – or None if unsuccessful and silent flag is set to True
- Return type:
int
Notes
see https://developers.google.com/drive/api/v3/manage-uploads