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:
ApiAttributeMixin
,ApiResource
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.
- 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, settings=None)¶
Bases:
ApiAttributeMixin
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. :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.
- Returns:
str – code returned from local web server
- Raises:
AuthenticationRejected, AuthenticationError
- Refresh()¶
Refreshes the access_token.
- Raises:
RefreshError
- SERVICE_CONFIGS_LIST = ['client_user_email']¶
- 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.
pydrive2.drive module¶
- class pydrive2.drive.GoogleDrive(auth=None)¶
Bases:
ApiAttributeMixin
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:
ApiAttributeMixin
,ApiResource
Google 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.
- 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, acknowledge_abuse=False)¶
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 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)¶
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.
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:
str – utf-8 decoded content of the file
- Raises:
ApiRequestError, FileNotUploadedError, FileNotDownloadableError
- GetPermissions()¶
Get file’s or shared drive’s permissions.
For files in a shared drive, at most 100 results will be returned. It doesn’t paginate and collect all results.
- Returns:
A list of the permission objects.
- Return type:
object[]
- GetRevisions()¶
Get file’s or shared drive’s revisions.
For files in a shared drive, at most 100 results will be returned. It doesn’t paginate and collect all results.
- Returns:
A list of the revision 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 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)¶
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:
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
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
pydrive2.fs module¶
- class pydrive2.fs.GDriveFileSystem(*args, **kwargs)¶
Bases:
AbstractFileSystem
Access to gdrive as an fsspec filesystem