Python API reference¶
Use GoogleAuth to authenticate and
GoogleDrive to work with files and listings. For
path-based operations, see fsspec filesystem.
pydrive2.apiattr module¶
- class pydrive2.apiattr.ApiAttribute(name)¶
Bases:
objectA data descriptor that sets and returns values.
- class pydrive2.apiattr.ApiAttributeMixin¶
Bases:
objectMixin to initialize required global variables to use ApiAttribute.
- class pydrive2.apiattr.ApiResource(*args, **kwargs)¶
Bases:
dictSuper class of all api resources.
Inherits and behaves as a python dictionary to handle api resources. Save clean copy of metadata in self.metadata as a dictionary. Provides changed metadata elements to efficiently update api resources.
- GetChanges()¶
Returns changed metadata elements to update api resources efficiently.
- Returns:
dict – changed metadata elements.
- UpdateMetadata(metadata=None)¶
Update metadata and mark all of them to be clean.
- auth¶
A data descriptor that sets and returns values.
- class pydrive2.apiattr.ApiResourceList(auth=None, metadata=None)¶
Bases:
ApiAttributeMixin,ApiResourceAbstract class of all api list resources.
Inherits ApiResource and builds iterator to list any API resource.
- GetList()¶
Get list of API resources.
If ‘pageSize’ is not specified, it will automatically iterate through every resources available. Otherwise, it will make API call once and update ‘pageToken’.
- Returns:
list – list of API resources.
- Reset()¶
Resets current iteration
- metadata¶
A data descriptor that sets and returns values.
pydrive2.auth module¶
- exception pydrive2.auth.AuthError¶
Bases:
ExceptionBase error for authentication/authorization errors.
- class pydrive2.auth.GoogleAuth(settings_file='settings.yaml', http_timeout=None, settings=None)¶
Bases:
ApiAttributeMixinGoogle Drive authentication using google-auth.
Reads authentication settings from a dictionary or YAML file. User tokens can be cached in a separate file or dictionary.
- Auth(code)¶
Authenticate, authorize, and build service.
- Parameters:
code (str.) – Code for authentication.
- Raises:
AuthenticationError
- Authenticate(code)¶
Authenticates given authentication code back from user.
- Parameters:
code (str.) – Code for authentication.
- Raises:
AuthenticationError
- Authorize()¶
Authorizes and builds service.
- Raises:
AuthenticationError
- CLIENT_CONFIGS_LIST: ClassVar[list[str]] = ['client_id', 'client_secret', 'auth_uri', 'token_uri', 'revoke_uri', 'redirect_uri']¶
- CommandLineAuth()¶
Print a login URL and receive the authorization on a local port.
- DEFAULT_SETTINGS: ClassVar[dict[str, str | bool | list[str]]] = {'client_config_backend': 'file', 'client_config_file': 'client_secrets.json', 'oauth_scope': ['https://www.googleapis.com/auth/drive'], 'save_credentials': False}¶
- GetAuthUrl()¶
Creates authentication url where user visits to grant access.
- Returns:
str – Authentication url.
- GetFlow()¶
Gets Flow object from client configuration.
- Raises:
InvalidConfigError
- Get_Http_Object()¶
Create and authorize an httplib2.Http object. Necessary for thread-safety. :return: The http object to be used in each call. :rtype: httplib2.Http
- LoadClientConfig(backend=None)¶
Loads client configuration according to specified backend.
If you have any specific backend to load client configuration from in mind, don’t use this function and use the corresponding function you want.
- Parameters:
backend (str.) – backend to load client configuration from.
- Raises:
InvalidConfigError
- LoadClientConfigFile(client_config_file=None)¶
Loads client configuration file downloaded from APIs console.
Loads client config file from path in settings if not specified.
- Parameters:
client_config_file (str.) – path of client config file to read.
- Raises:
InvalidConfigError
- LoadClientConfigSettings()¶
Loads client configuration from settings file.
- Raises:
InvalidConfigError
- LoadCredentials(backend=None)¶
Load user credentials, setting credentials to None if the cache is empty.
- Parameters:
backend (str.) – target backend to save credential to.
- Raises:
InvalidConfigError
- LoadCredentialsFile(credentials_file=None)¶
Load user credentials, setting credentials to None if the cache is empty.
Loads credentials file from path in settings if not specified.
- Parameters:
credentials_file (str.) – path of credentials file to read.
- Raises:
InvalidConfigError, InvalidCredentialsError
- LoadServiceConfigSettings()¶
Loads client configuration from settings. :raises: InvalidConfigError
- LocalWebserverAuth(host_name='localhost', port_numbers=None, launch_browser=True, bind_addr=None)¶
Authenticate and authorize from user by creating local web server and retrieving authentication code.
This function is not for web server application. It creates local web server for user from standalone application.
If GDRIVE_NON_INTERACTIVE environment variable is set, this function raises AuthenticationError.
- Parameters:
host_name (str.) – host name of the local web server.
port_numbers (list.) – list of port numbers to be tried to used.
launch_browser (bool) – should browser be launched automatically
bind_addr (str.) – optional IP address for the local web server to listen on. If not specified, it will listen on the address specified in the host_name parameter.
- Raises:
AuthenticationRejected, AuthenticationError
- Refresh()¶
Refreshes the access_token.
- Raises:
RefreshError
- SaveCredentials(backend=None)¶
Saves credentials according to specified backend.
If you have any specific credentials backend in mind, don’t use this function and use the corresponding function you want.
- Parameters:
backend (str.) – backend to save credentials.
- Raises:
InvalidConfigError
- SaveCredentialsFile(credentials_file=None)¶
Saves credentials to the file in JSON format.
- Parameters:
credentials_file (str.) – destination to save file to.
- Raises:
InvalidConfigError, InvalidCredentialsError
- ServiceAuth()¶
Authenticate with a service account, optionally acting for a user.
- property access_token_expired¶
Checks if access token doesn’t exist or is expired.
- Returns:
bool – True if access token doesn’t exist or is expired.
- auth_method¶
A data descriptor that sets and returns values.
- client_config¶
A data descriptor that sets and returns values.
- property credentials¶
- flow¶
A data descriptor that sets and returns values.
- http¶
A data descriptor that sets and returns values.
- service¶
A data descriptor that sets and returns values.
- settings¶
A data descriptor that sets and returns values.
- pydrive2.auth.LoadAuth(decoratee)¶
Decorator to check if the auth is valid and loads auth if not.
pydrive2.drive module¶
- class pydrive2.drive.GoogleDrive(auth=None)¶
Bases:
ApiAttributeMixinMain Google Drive class.
- CreateFile(metadata=None)¶
Create an instance of GoogleDriveFile with auth of this instance.
This method would not upload a file to GoogleDrive.
- Parameters:
metadata (dict.) – file resource to initialize GoogleDriveFile with.
- Returns:
pydrive2.files.GoogleDriveFile – initialized with auth of this instance.
- GetAbout(fields='*')¶
Return information about the Google Drive of the auth instance.
- Parameters:
fields – Drive About fields to return. Defaults to all fields.
- Returns:
A dictionary of Google Drive information like user, usage, quota etc.
- ListFile(param=None)¶
Create an instance of GoogleDriveFileList with auth of this instance.
This method will not fetch from Files.List().
- Parameters:
param (dict.) – parameter to be sent to Files.List().
- Returns:
pydrive2.files.GoogleDriveFileList – initialized with auth of this instance.
pydrive2.files module¶
- exception pydrive2.files.ApiRequestError(http_error)¶
Bases:
OSError- GetField(field)¶
Returns the field from the first error
- exception pydrive2.files.FileNotDownloadableError¶
Bases:
RuntimeErrorError trying to download file that is not downloadable.
- exception pydrive2.files.FileNotUploadedError¶
Bases:
RuntimeErrorError trying to access metadata of file that is not uploaded.
- class pydrive2.files.GoogleDriveFile(auth=None, metadata=None, uploaded=False)¶
Bases:
ApiAttributeMixin,ApiResourceGoogle Drive File instance.
Inherits ApiResource which inherits dict. Can access and modify metadata like dictionary.
- Copy(target_folder=None, new_title=None, param=None)¶
Creates a copy of this file. Folders cannot be copied.
- Parameters:
target_folder (GoogleDriveFile, optional) – Folder where the file will be copied.
new_title (str, optional) – Name of the new file.
param (dict, optional) – addition parameters to pass.
- Raises:
ApiRequestError
- Returns:
the copied file
- Return type:
- Delete(param=None)¶
Hard-delete a file.
- Parameters:
param (dict.) – additional parameter to file.
- Raises:
ApiRequestError
- DeletePermission(permission_id)¶
Deletes the permission specified by the permission_id.
- Parameters:
permission_id (str) – The permission id.
- FetchContent(mimetype=None, remove_bom=False)¶
Download file content or a Workspace export into memory.
- FetchMetadata(fields=None, fetch_all=False)¶
Download file’s metadata from id using Files.get().
- Parameters:
fields (str) – The fields to include, as one string, each entry separated by commas, e.g. ‘id,name,trashed’.
fetch_all (bool) – Whether to fetch all fields.
- Raises:
ApiRequestError, FileNotUploadedError
- GetContentFile(filename, mimetype=None, remove_bom=False, callback=None, chunksize=104857600, acknowledge_abuse=False)¶
Save content of this file as a local file.
The destination is opened after the first successful read. If a later read fails, the destination contains the chunks written so far.
- Parameters:
filename (str) – name of the file to write to.
mimetype (str) – mimeType of the file.
remove_bom (bool) – Whether to remove the byte order marking.
callback – passed two arguments: (total transferred, file size).
chunksize (int) – chunksize in bytes (standard 100 MB(1024*1024*100))
acknowledge_abuse (bool) – Acknowledging the risk and download file identified as abusive.
- Raises:
ApiRequestError, FileNotUploadedError
- GetContentIOBuffer(mimetype=None, encoding=None, remove_bom=False, chunksize=104857600, acknowledge_abuse=False)¶
Return a sequential reader over Drive download or export chunks.
Iterate over the reader or call its read() method once per chunk. Chunks are bytes unless an encoding is supplied.
- Parameters:
mimetype (str) – mimeType of the file.
encoding (str) – The encoding to use when decoding the byte string.
remove_bom (bool) – Whether to remove the byte order marking.
chunksize (int) – default read()/iter() chunksize.
acknowledge_abuse (bool) – Acknowledging the risk and download file identified as abusive.
- Returns:
MediaIoReadable – file-like object.
- Raises:
ApiRequestError, FileNotUploadedError
- GetContentString(mimetype=None, encoding='utf-8', remove_bom=False)¶
Get content of this file as a string.
- Parameters:
mimetype (str) – The mimetype of the content string.
encoding (str) – The encoding to use when decoding the byte string.
remove_bom (bool) – Whether to strip a known BOM.
- Returns:
File content decoded with the requested encoding.
- Raises:
ApiRequestError, FileNotUploadedError, FileNotDownloadableError
- GetPermissions()¶
Return all permissions for the file, including shared drive files.
- GetRevisions()¶
Return all revisions visible to the authenticated user.
- InsertPermission(new_permission, param=None)¶
Insert a new permission. Re-fetches all permissions after call.
- Parameters:
new_permission (object) – The new permission to insert, please see the official Google Drive API guide on permissions.create for details.
param (dict) – addition parameters to pass
- Returns:
The permission object.
- Return type:
object
- SetContentFile(filename)¶
Open a local file for upload.
Sets metadata ‘name’ and ‘mimeType’ automatically if not specified and the file is uploaded for the first time (id is not set).
- Parameters:
filename (str.) – name of the file to be uploaded.
- SetContentString(content, encoding='utf-8')¶
Set content of this file to be a string.
Creates io.BytesIO instance of utf-8 encoded string. Sets mimeType to be ‘text/plain’ if not specified and file id is not set (means that we are uploading this file for the first time).
- Parameters:
encoding (str) – The encoding to use when setting the content of this file.
content (str) – content of the file in string.
- Trash(param=None)¶
Move a file to the trash.
- Raises:
ApiRequestError
- UnTrash(param=None)¶
Move a file out of the trash. :param param: Additional parameter to file. :type param: dict. :raises: ApiRequestError
- Upload(param=None, *, media_mime_type=None)¶
Create or update a file, optionally importing uploaded media.
For a Workspace import, set the destination MIME type in the file metadata and pass the source MIME type as media_mime_type.
- property content¶
- metadata¶
A data descriptor that sets and returns values.
- uploaded¶
A data descriptor that sets and returns values.
- class pydrive2.files.GoogleDriveFileList(auth=None, param=None)¶
Bases:
ApiResourceListGoogle Drive FileList instance.
Equivalent to Files.list() in Drive APIs.
- class pydrive2.files.IoBuffer¶
Bases:
objectLightweight retention of one chunk.
- read()¶
- write(chunk)¶
- pydrive2.files.LoadMetadata(decoratee)¶
Decorator to check if the file has metadata and fetches it if not.
- Raises:
ApiRequestError, FileNotUploadedError
pydrive2.settings module¶
- exception pydrive2.settings.InvalidConfigError¶
Bases:
OSErrorError trying to read client configuration.
- pydrive2.settings.LoadSettingsFile(filename='settings.yaml')¶
Loads settings file in yaml format given file name.
- Parameters:
filename (str.) – path for settings file. ‘settings.yaml’ by default.
- Raises:
SettingsError
- exception pydrive2.settings.SettingsError¶
Bases:
OSErrorError while loading/saving settings
- pydrive2.settings.ValidateSettings(data)¶
Validates if current settings is valid.
- Parameters:
data (dict.) – dictionary containing all settings.
- Raises:
InvalidConfigError
pydrive2.fs module¶
- class pydrive2.fs.GDriveFileSystem(*args, **kwargs)¶
Bases:
AbstractFileSystemAccess to gdrive as an fsspec filesystem
- __init__(path='root', google_auth=None, client_id=None, client_secret=None, client_user_email=None, client_json=None, client_json_file_path=None, use_service_account=False, profile=None, trash_only=True, acknowledge_abuse=False, **kwargs)¶
Create an instance of GDriveFileSystem.
- Parameters:
path (str.) – gdrive path. Defaults to
"root"(the Drive root), sofsspeccan build the filesystem without one.google_auth (GoogleAuth.) – Authenticated GoogleAuth instance.
client_id (str) – Client ID of the application.
client_secret (str.) – Client secret of the application.
client_user_email (str.) – User email that authority was delegated to (only for service account).
client_json (str.) – Saved user credentials or a service-account key as JSON.
client_json_file_path (str.) – User token cache or service-account key path.
use_service_account (bool.) – Use service account.
profile (str.) – Profile name for caching credentials (ignored for service account).
trash_only (bool.) – Move files to trash instead of deleting.
acknowledge_abuse (bool) – Acknowledging the risk and download file identified as abusive.
- Raises:
GDriveAuthError