pydrive package

pydrive.apiattr module

class pydrive.apiattr.ApiAttribute(name)

Bases: object

A data descriptor that sets and returns values.

class pydrive.apiattr.ApiAttributeMixin

Bases: object

Mixin to initialize required global variables to use ApiAttribute.

class pydrive.apiattr.ApiResource(*args, **kwargs)

Bases: dict

Super 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.

update(*args, **kwargs)

Overwritten method of dictionary.

class pydrive.apiattr.ApiResourceList(auth=None, metadata=None)

Bases: pydrive.apiattr.ApiAttributeMixin, pydrive.apiattr.ApiResource, six.Iterator

Abstract class of all api list resources.

Inherits ApiResource and builds iterator to list any API resource.

GetList()

Get list of API resources.

If ‘maxResults’ 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.

pydrive.auth module

exception pydrive.auth.AuthError

Bases: exceptions.Exception

Base error for authentication/authorization errors.

exception pydrive.auth.AuthenticationError

Bases: pydrive.auth.AuthError

General authentication error.

exception pydrive.auth.AuthenticationRejected

Bases: pydrive.auth.AuthError

User rejected authentication.

pydrive.auth.CheckAuth(decoratee)

Decorator to check if it requires OAuth2 flow request.

pydrive.auth.CheckServiceAuth(decoratee)

Decorator to authorize service account.

class pydrive.auth.GoogleAuth(settings_file='settings.yaml', http_timeout=None)

Bases: pydrive.apiattr.ApiAttributeMixin, object

Wrapper class for oauth2client library in google-api-python-client.

Loads all settings and credentials from one ‘settings.yaml’ file and performs common OAuth2.0 related functionality such as authentication and authorization.

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 = ['client_id', 'client_secret', 'auth_uri', 'token_uri', 'revoke_uri', 'redirect_uri']
CommandLineAuth(*args, **kwargs)

Authenticate and authorize from user by printing authentication url retrieving authentication code from command-line.

Returns:str – code returned from commandline.
DEFAULT_SETTINGS = {'save_credentials': False, 'client_config_file': 'client_secrets.json', 'client_config_backend': 'file', 'oauth_scope': ['https://www.googleapis.com/auth/drive']}
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)

Loads credentials or create empty credentials if it doesn’t exist.

Parameters:backend (str.) – target backend to save credential to.
Raises:InvalidConfigError
LoadCredentialsFile(credentials_file=None)

Loads credentials or create empty credentials if it doesn’t exist.

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 file. :raises: InvalidConfigError

LocalWebserverAuth(*args, **kwargs)

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.

Parameters:
  • host_name (str.) – host name of the local web server.
  • port_numbers (list.) – list of port numbers to be tried to used.
Returns:

str – code returned from local web server

Raises:

AuthenticationRejected, AuthenticationError

Refresh()

Refreshes the access_token.

Raises:RefreshError
SERVICE_CONFIGS_LIST = ['client_service_email', 'client_user_email', 'client_pkcs12_file_path']
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(*args, **kwargs)

Authenticate and authorize using P12 private key, client id and client email for a Service account. :raises: AuthError, InvalidConfigError

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.

credentials

A data descriptor that sets and returns values.

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.

exception pydrive.auth.InvalidCredentialsError

Bases: exceptions.IOError

Error trying to read credentials file.

pydrive.auth.LoadAuth(decoratee)

Decorator to check if the auth is valid and loads auth if not.

exception pydrive.auth.RefreshError

Bases: pydrive.auth.AuthError

Access token refresh error.

pydrive.drive module

class pydrive.drive.GoogleDrive(auth=None)

Bases: pydrive.apiattr.ApiAttributeMixin, object

Main 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:pydrive.files.GoogleDriveFile – initialized with auth of this instance.
GetAbout(*args, **kwargs)

Return information about the Google Drive of the auth instance.

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:pydrive.files.GoogleDriveFileList – initialized with auth of this instance.

pydrive.files module

exception pydrive.files.ApiRequestError

Bases: exceptions.IOError

Error while making any API requests.

exception pydrive.files.FileNotDownloadableError

Bases: exceptions.RuntimeError

Error trying to download file that is not downloadable.

exception pydrive.files.FileNotUploadedError

Bases: exceptions.RuntimeError

Error trying to access metadata of file that is not uploaded.

class pydrive.files.GoogleDriveFile(auth=None, metadata=None, uploaded=False)

Bases: pydrive.apiattr.ApiAttributeMixin, pydrive.apiattr.ApiResource

Google Drive File instance.

Inherits ApiResource which inherits dict. Can access and modify metadata like dictionary.

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.
Returns:True if it succeeds.
Return type:bool
FetchContent(*args, **kwargs)

Download file’s content from download_url.

Raises:ApiRequestError, FileNotUploadedError, FileNotDownloadableError
FetchMetadata(*args, **kwargs)

Download file’s metadata from id using Files.get().

Parameters:fields – The fields to include, as one string, each entry separated

by commas, e.g. ‘fields,labels’. :type fields: str

Parameters:fetch_all (bool) – Whether to fetch all fields.
Raises:ApiRequestError, FileNotUploadedError
GetContentFile(filename, mimetype=None)

Save content of this file as a local file.

Parameters:
  • filename (str) – name of the file to write to.
  • mimetype (str) – mimeType of the file.
Raises:

ApiRequestError, FileNotUploadedError, FileNotDownloadableError

GetContentString(mimetype=None)

Get content of this file as a string.

Returns:str – utf-8 decoded content of the file
Raises:ApiRequestError, FileNotUploadedError, FileNotDownloadableError
GetPermissions(*args, **kwargs)

Downloads all permissions from Google Drive, as this information is not downloaded by FetchMetadata by default.

Returns:A list of the permission objects.
Return type:object[]
InsertPermission(new_permission)

Insert a new permission. Re-fetches all permissions after call.

Parameters:new_permission – The new permission to insert, please see the

official Google Drive API guide on permissions.insert for details.

Returns:The permission object.
Return type:object
SetContentFile(filename)

Set content of this file from a file.

Opens the file specified by this method. Will be read, uploaded, and closed by Upload() method. Sets metadata ‘title’ and ‘mimeType’ automatically if not specified.

Parameters:filename (str.) – name of the file to be uploaded.
SetContentString(content)

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.

Parameters: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)

Upload/update file by choosing the most efficient method.

Parameters:param (dict.) – additional parameter to upload file.
Raises:ApiRequestError
content

A data descriptor that sets and returns values.

metadata

A data descriptor that sets and returns values.

uploaded

A data descriptor that sets and returns values.

class pydrive.files.GoogleDriveFileList(auth=None, param=None)

Bases: pydrive.apiattr.ApiResourceList

Google Drive FileList instance.

Equivalent to Files.list() in Drive APIs.

pydrive.files.LoadMetadata(decoratee)

Decorator to check if the file has metadata and fetches it if not.

Raises:ApiRequestError, FileNotUploadedError

pydrive.settings module

exception pydrive.settings.InvalidConfigError

Bases: exceptions.IOError

Error trying to read client configuration.

pydrive.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 pydrive.settings.SettingsError

Bases: exceptions.IOError

Error while loading/saving settings

pydrive.settings.ValidateSettings(data)

Validates if current settings is valid.

Parameters:data (dict.) – dictionary containing all settings.
Raises:InvalidConfigError