pydrive2 package

pydrive2.apiattr module

class pydrive2.apiattr.ApiAttribute(name)

Bases: object

A data descriptor that sets and returns values.

class pydrive2.apiattr.ApiAttributeMixin

Bases: object

Mixin to initialize required global variables to use ApiAttribute.

class pydrive2.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 pydrive2.apiattr.ApiResourceList(auth=None, metadata=None)

Bases: pydrive2.apiattr.ApiAttributeMixin, pydrive2.apiattr.ApiResource, object

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.

pydrive2.auth module

exception pydrive2.auth.AuthError

Bases: Exception

Base error for authentication/authorization errors.

exception pydrive2.auth.AuthenticationError

Bases: pydrive2.auth.AuthError

General authentication error.

exception pydrive2.auth.AuthenticationRejected

Bases: pydrive2.auth.AuthError

User rejected authentication.

pydrive2.auth.CheckAuth(decoratee)

Decorator to check if it requires OAuth2 flow request.

pydrive2.auth.CheckServiceAuth(decoratee)

Decorator to authorize service account.

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

Bases: pydrive2.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()

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

Returns

str – code returned from commandline.

DEFAULT_SETTINGS = {'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)

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(host_name='localhost', port_numbers=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.

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()

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

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.

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 pydrive2.auth.InvalidCredentialsError

Bases: OSError

Error trying to read credentials file.

pydrive2.auth.LoadAuth(decoratee)

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

exception pydrive2.auth.RefreshError

Bases: pydrive2.auth.AuthError

Access token refresh error.

pydrive2.drive module

class pydrive2.drive.GoogleDrive(auth=None)

Bases: pydrive2.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

pydrive2.files.GoogleDriveFile – initialized with auth of this instance.

GetAbout()

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

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: RuntimeError

Error trying to download file that is not downloadable.

exception pydrive2.files.FileNotUploadedError

Bases: RuntimeError

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

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

Bases: pydrive2.apiattr.ApiAttributeMixin, pydrive2.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(mimetype=None, remove_bom=False)

Download file’s content from download_url.

Raises

ApiRequestError, FileNotUploadedError, FileNotDownloadableError

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. ‘fields,labels’.

  • fetch_all (bool) – Whether to fetch all fields.

Raises

ApiRequestError, FileNotUploadedError

GetContentFile(filename, mimetype=None, remove_bom=False, callback=None, chunksize=104857600)

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.

  • remove_bom (bool) – Whether to remove the byte order marking.

  • callback – passed two arguments: (total trasferred, file size).

  • chunksize (int) – chunksize in bytes (standard 100 MB(1024*1024*100))

Raises

ApiRequestError, FileNotUploadedError

GetContentIOBuffer(mimetype=None, encoding=None, remove_bom=False, chunksize=104857600)

Get a file-like object which has a buffered read() method.

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.

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

str – utf-8 decoded content of the file

Raises

ApiRequestError, FileNotUploadedError, FileNotDownloadableError

GetPermissions()

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, 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.insert for details.

  • param (dict) – addition parameters to pass

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

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)

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 pydrive2.files.GoogleDriveFileList(auth=None, param=None)

Bases: pydrive2.apiattr.ApiResourceList

Google Drive FileList instance.

Equivalent to Files.list() in Drive APIs.

class pydrive2.files.IoBuffer(encoding)

Bases: object

Lightweight 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

class pydrive2.files.MediaIoReadable(request, encoding=None, pre_buffer=True, remove_prefix=b'', chunksize=104857600)

Bases: object

read()
Returns

bytes or str – chunk (or None if done)

Raises

ApiRequestError

pydrive2.settings module

exception pydrive2.settings.InvalidConfigError

Bases: OSError

Error 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: OSError

Error while loading/saving settings

pydrive2.settings.ValidateSettings(data)

Validates if current settings is valid.

Parameters

data (dict.) – dictionary containing all settings.

Raises

InvalidConfigError