msl.io.google_api module

Wrappers around Google APIs:

class msl.io.google_api.GDrive(account=None, credentials=None, read_only=True, scopes=None)[source]

Bases: GoogleAPI

Interact with Google Drive.

Attention

You must follow the instructions in the prerequisites section for setting up the Drive API before you can use this class. It is also useful to be aware of the refresh token expiration policy.

Parameters:
  • account (str, optional) – Since a person may have multiple Google accounts, and multiple people may run the same code, this parameter decides which token to load to authenticate with the Google API. The value can be any text (or None) that you want to associate with a particular Google account, provided that it contains valid characters for a filename. The value that you chose when you authenticated with your credentials should be used for all future instances of this class to access that particular Google account. You can associate a different value with a Google account at any time (by passing in a different account value), but you will be asked to authenticate with your credentials again, or, alternatively, you can rename the token files located in HOME_DIR to match the new account value.

  • credentials (str, optional) – The path to the client secrets OAuth credential file. This parameter only needs to be specified the first time that you authenticate with a particular Google account or if you delete the token file that was created when you previously authenticated.

  • read_only (bool, optional) – Whether to interact with Google Drive in read-only mode.

  • scopes (list of str, optional) – The list of scopes to enable for the Google API. See Drive scopes for more details. If not specified then default scopes are chosen based on the value of read_only.

MIME_TYPE_FOLDER = 'application/vnd.google-apps.folder'
ROOT_NAMES = ['Google Drive', 'My Drive', 'Drive']
copy(file_id, folder_id=None, name=None)[source]

Copy a file.

Parameters:
  • file_id (str) – The ID of a file to copy. Folders cannot be copied.

  • folder_id (str, optional) – The ID of the destination folder. If not specified then creates a copy in the same folder that the original file is located in. To copy the file to the My Drive root folder then specify 'root' as the folder_id.

  • name (str, optional) – The filename of the destination file.

Returns:

str – The ID of the destination file.

create_folder(folder, parent_id=None)[source]

Create a folder.

Makes all intermediate-level folders needed to contain the leaf directory.

Parameters:
  • folder (str) – The folder(s) to create, for example, 'folder1' or 'folder1/folder2/folder3'.

  • parent_id (str, optional) – The ID of the parent folder that folder is relative to. If not specified then folder is relative to the My Drive root folder. If folder is in a Shared drive then you must specify the ID of a parent folder.

Returns:

str – The ID of the last (right most) folder that was created.

delete(file_or_folder_id)[source]

Delete a file or a folder.

Files that are in read-only mode cannot be deleted.

Danger

Permanently deletes the file or folder owned by the user without moving it to the trash. If the target is a folder, then all files and sub-folders contained within the folder (that are owned by the user) are also permanently deleted.

Parameters:

file_or_folder_id (str) – The ID of the file or folder to delete.

download(file_id, save_to=None, num_retries=0, chunk_size=104857600, callback=None)[source]

Download a file.

Parameters:
  • file_id (str) – The ID of the file to download.

  • save_to (path-like or file-like, optional) – The location to save the file to. If a directory is specified then the file will be saved to that directory using the filename of the remote file. To save the file with a new filename, specify the new filename in save_to. Default is to save the file to the current working directory using the remote filename.

  • num_retries (int, optional) – The number of times to retry the download. If zero (default) then attempt the request only once.

  • chunk_size (int, optional) – The file will be downloaded in chunks of this many bytes.

  • callback

    The callback to call after each chunk of the file is downloaded. The callback accepts one positional argument, for example:

    def handler(file):
        print(file.progress(), file.total_size, file.resumable_progress)
    
    drive.download('0Bwab3C2ejYSdM190b2psXy1C50P', callback=handler)
    

empty_trash()[source]

Permanently delete all files in the trash.

file_id(file, mime_type=None, folder_id=None)[source]

Get the ID of a Google Drive file.

Parameters:
  • file (str) – The path to a Google Drive file.

  • mime_type (str, optional) – The Drive MIME type or Media type to use to filter the results.

  • folder_id (str, optional) – The ID of the folder that file is relative to. If not specified then file is relative to the My Drive root folder. If file is in a Shared drive then you must specify the ID of a parent folder.

Returns:

str – The file ID.

folder_id(folder, parent_id=None)[source]

Get the ID of a Google Drive folder.

Parameters:
  • folder (str) – The path to a Google Drive file.

  • parent_id (str, optional) – The ID of the parent folder that folder is relative to. If not specified then folder is relative to the My Drive root folder. If folder is in a Shared drive then you must specify the ID of a parent folder.

Returns:

str – The folder ID.

is_file(file, mime_type=None, folder_id=None)[source]

Check if a file exists.

Parameters:
  • file (str) – The path to a Google Drive file.

  • mime_type (str, optional) – The Drive MIME type or Media type to use to filter the results.

  • folder_id (str, optional) – The ID of the folder that file is relative to. If not specified then file is relative to the My Drive root folder. If file is in a Shared drive then you must specify the ID of a parent folder.

Returns:

bool – Whether the file exists.

is_folder(folder, parent_id=None)[source]

Check if a folder exists.

Parameters:
  • folder (str) – The path to a Google Drive folder.

  • parent_id (str, optional) – The ID of the parent folder that folder is relative to. If not specified then folder is relative to the My Drive root folder. If folder is in a Shared drive then you must specify the ID of a parent folder.

Returns:

bool – Whether the folder exists.

is_read_only(file_id)[source]

Returns whether the file is in read-only mode.

Parameters:

file_id (str) – The ID of a file.

Returns:

bool – Whether the file is in read-only mode.

move(source_id, destination_id)[source]

Move a file or a folder.

When moving a file or folder between My Drive and a Shared drive the access permissions will change.

Moving a file or folder does not change its ID, only the ID of its parent changes (i.e., source_id will remain the same after the move).

Parameters:
  • source_id (str) – The ID of a file or folder to move.

  • destination_id (str) – The ID of the destination folder. To move the file or folder to the My Drive root folder then specify 'root' as the destination_id.

path(file_or_folder_id)[source]

Convert an ID to a path.

Parameters:

file_or_folder_id (str) – The ID of a file or folder.

Returns:

str – The corresponding path of the ID.

read_only(file_id, read_only, reason='')[source]

Set a file to be in read-only mode.

Parameters:
  • file_id (str) – The ID of a file.

  • read_only (bool) – Whether to set the file to be in read-only mode.

  • reason (str, optional) – The reason for putting the file in read-only mode. Only used if read_only is True.

rename(file_or_folder_id, new_name)[source]

Rename a file or folder.

Renaming a file or folder does not change its ID.

Parameters:
  • file_or_folder_id (str) – The ID of a file or folder.

  • new_name (str) – The new name of the file or folder.

shared_drives()[source]

Returns the IDs and names of all Shared drives.

Returns:

dict – The keys are the IDs of the shared drives and the values are the names of the shared drives.

upload(file, folder_id=None, mime_type=None, resumable=False, chunk_size=104857600)[source]

Upload a file.

Parameters:
  • file (str) – The file to upload.

  • folder_id (str, optional) – The ID of the folder to upload the file to. If not specified then uploads to the My Drive root folder.

  • mime_type (str, optional) – The Drive MIME type or Media type of the file (e.g., 'text/csv'). If not specified then a type will be guessed based on the file extension.

  • resumable (bool) – Whether the upload can be resumed.

  • chunk_size (int) – The file will be uploaded in chunks of this many bytes. Only used if resumable is True. Pass in a value of -1 if the file is to be uploaded in a single chunk. Note that Google App Engine has a 5MB limit on request size, so you should never set chunk_size to be >5MB or to -1 (if the file size is >5MB).

Returns:

str – The ID of the file that was uploaded.

class msl.io.google_api.GMail(account=None, credentials=None, scopes=None)[source]

Bases: GoogleAPI

Interact with Gmail.

Attention

You must follow the instructions in the prerequisites section for setting up the Gmail API before you can use this class. It is also useful to be aware of the refresh token expiration policy.

Parameters:
  • account (str, optional) – Since a person may have multiple Google accounts, and multiple people may run the same code, this parameter decides which token to load to authenticate with the Google API. The value can be any text (or None) that you want to associate with a particular Google account, provided that it contains valid characters for a filename. The value that you chose when you authenticated with your credentials should be used for all future instances of this class to access that particular Google account. You can associate a different value with a Google account at any time (by passing in a different account value), but you will be asked to authenticate with your credentials again, or, alternatively, you can rename the token files located in HOME_DIR to match the new account value.

  • credentials (str, optional) – The path to the client secrets OAuth credential file. This parameter only needs to be specified the first time that you authenticate with a particular Google account or if you delete the token file that was created when you previously authenticated.

  • scopes (list of str, optional) – The list of scopes to enable for the Google API. See Gmail scopes for more details. If not specified then default scopes are chosen.

profile()[source]

Gets the authenticated user’s Gmail profile.

Returns:

dict – Returns the following

{
   'email_address': string, The authenticated user's email address
   'messages_total': integer, The total number of messages in the mailbox
   'threads_total': integer, The total number of threads in the mailbox
   'history_id': string, The ID of the mailbox's current history record
}

send(recipients, sender='me', subject=None, body=None)[source]

Send an email.

Parameters:
  • recipients (str or list of str) – The email address(es) of the recipient(s). The value 'me' can be used to indicate the authenticated user.

  • sender (str, optional) – The email address of the sender. The value 'me' can be used to indicate the authenticated user.

  • subject (str, optional) – The text to include in the subject field.

  • body (str, optional) – The text to include in the body of the email. The text can be enclosed in <html></html> tags to use HTML elements to format the message.

See also

send_email()

class msl.io.google_api.GSheets(account=None, credentials=None, read_only=True, scopes=None)[source]

Bases: GoogleAPI

Interact with Google Sheets.

Attention

You must follow the instructions in the prerequisites section for setting up the Sheets API before you can use this class. It is also useful to be aware of the refresh token expiration policy.

Parameters:
  • account (str, optional) – Since a person may have multiple Google accounts, and multiple people may run the same code, this parameter decides which token to load to authenticate with the Google API. The value can be any text (or None) that you want to associate with a particular Google account, provided that it contains valid characters for a filename. The value that you chose when you authenticated with your credentials should be used for all future instances of this class to access that particular Google account. You can associate a different value with a Google account at any time (by passing in a different account value), but you will be asked to authenticate with your credentials again, or, alternatively, you can rename the token files located in HOME_DIR to match the new account value.

  • credentials (str, optional) – The path to the client secrets OAuth credential file. This parameter only needs to be specified the first time that you authenticate with a particular Google account or if you delete the token file that was created when you previously authenticated.

  • read_only (bool, optional) – Whether to interact with Google Sheets in read-only mode.

  • scopes (list of str, optional) – The list of scopes to enable for the Google API. See Sheets scopes for more details. If not specified then default scopes are chosen based on the value of read_only.

MIME_TYPE = 'application/vnd.google-apps.spreadsheet'
SERIAL_NUMBER_ORIGIN = datetime.datetime(1899, 12, 30, 0, 0)
add_sheets(names, spreadsheet_id)[source]

Add sheets to a spreadsheet.

Parameters:
  • names (str or list of str) – The name(s) of the new sheet(s) to add.

  • spreadsheet_id (str) – The ID of the spreadsheet to add the sheet(s) to.

Returns:

dict – The keys are the IDs of the new sheets and the values are the names.

append(values, spreadsheet_id, cell=None, sheet=None, row_major=True, raw=False)[source]

Append values to a sheet.

Returns:

  • values – The value(s) to append

  • spreadsheet_id (str) – The ID of a Google Sheets file.

  • cell (str, optional) – The cell (top-left corner) to start appending the values to. If the cell already contains data then new rows are inserted and the values are written to the new rows. For example, 'D100'.

  • sheet (str, optional) – The name of a sheet in the spreadsheet to append the values to. If not specified and only one sheet exists in the spreadsheet then automatically determines the sheet name; however, it is more efficient to specify the name of the sheet.

  • row_major (bool, optional) – Whether to append the values in row-major or column-major order.

  • raw (bool, optional) – Determines how the values should be interpreted. If True, the values will not be parsed and will be stored as-is. If False, the values will be parsed as if the user typed them into the UI. Numbers will stay as numbers, but strings may be converted to numbers, dates, etc. following the same rules that are applied when entering text into a cell via the Google Sheets UI.

cells(spreadsheet_id, ranges=None)[source]

Return cells from a spreadsheet.

Parameters:
  • spreadsheet_id (str) – The ID of a Google Sheets file.

  • ranges (str or list of str, optional) –

    The ranges to retrieve from the spreadsheet. Examples:

    • 'Sheet1' \(\rightarrow\) return all cells from the sheet named Sheet1

    • 'Sheet1!A1:H5' \(\rightarrow\) return cells A1:H5 from the sheet named Sheet1

    • ['Sheet1!A1:H5', 'Data', 'Devices!B4:B9'] \(\rightarrow\) return cells A1:H5 from the sheet named Sheet1, all cells from the sheet named Data and cells B4:B9 from the sheet named Devices

    If not specified then return all cells from all sheets.

Returns:

dict – The cells from the spreadsheet. The keys are the names of the sheets and the values are a list of GCell objects for the specified range of each sheet.

copy(name_or_id, spreadsheet_id, destination_spreadsheet_id)[source]

Copy a sheet from one spreadsheet to another spreadsheet.

Parameters:
  • name_or_id (str or int) – The name or ID of the sheet to copy.

  • spreadsheet_id (str) – The ID of the spreadsheet that contains the sheet.

  • destination_spreadsheet_id (str) – The ID of a spreadsheet to copy the sheet to.

Returns:

int – The ID of the sheet in the destination spreadsheet.

create(name, sheet_names=None)[source]

Create a new spreadsheet.

The spreadsheet will be created in the My Drive root folder. To move it to a different folder use GDrive.create_folder() and/or GDrive.move().

Parameters:
  • name (str) – The name of the spreadsheet.

  • sheet_names (list of str, optional) – The names of the sheets that are in the spreadsheet.

Returns:

str – The ID of the spreadsheet that was created.

delete_sheets(names_or_ids, spreadsheet_id)[source]

Delete sheets from a spreadsheet.

Parameters:
  • names_or_ids (str, int or list) – The name(s) or ID(s) of the sheet(s) to delete.

  • spreadsheet_id (str) – The ID of the spreadsheet to delete the sheet(s) from.

rename_sheet(name_or_id, new_name, spreadsheet_id)[source]

Rename a sheet.

Parameters:
  • name_or_id (str or int) – The name or ID of the sheet to rename.

  • new_name (str) – The new name of the sheet.

  • spreadsheet_id (str) – The ID of the spreadsheet that contains the sheet.

sheet_id(name, spreadsheet_id)[source]

Returns the ID of a sheet.

Parameters:
  • name (str) – The name of the sheet.

  • spreadsheet_id (str) – The ID of the spreadsheet.

Returns:

int – The ID of the sheet.

sheet_names(spreadsheet_id)[source]

Get the names of all sheets in a spreadsheet.

Parameters:

spreadsheet_id (str) – The ID of a Google Sheets file.

Returns:

tuple of str – The names of all sheets.

static to_datetime(value)[source]

Convert a “serial number” date into a datetime.datetime.

Parameters:

value (float) – A date in the “serial number” format.

Returns:

datetime.datetime – The date converted.

values(spreadsheet_id, sheet=None, cells=None, row_major=True, value_option=GValueOption.FORMATTED, datetime_option=GDateTimeOption.SERIAL_NUMBER)[source]

Return a range of values from a spreadsheet.

Parameters:
  • spreadsheet_id (str) – The ID of a Google Sheets file.

  • sheet (str, optional) – The name of a sheet in the spreadsheet to read the values from. If not specified and only one sheet exists in the spreadsheet then automatically determines the sheet name; however, it is more efficient to specify the name of the sheet.

  • cells (str, optional) – The A1 notation or R1C1 notation of the range to retrieve values from. If not specified then returns all values that are in sheet.

  • row_major (bool, optional) – Whether to return the values in row-major or column-major order.

  • value_option (str or GValueOption, optional) – How values should be represented in the output. If a string then it must be equal to one of the values in GValueOption.

  • datetime_option (str or GDateTimeOption, optional) – How dates, times, and durations should be represented in the output. If a string then it must be equal to one of the values in GDateTimeOption. This argument is ignored if value_option is GValueOption.FORMATTED.

Returns:

list – The values from the sheet.

write(values, spreadsheet_id, cell, sheet=None, row_major=True, raw=False)[source]

Write values to a sheet.

If a cell that is being written to already contains a value, the value in that cell is overwritten with the new value.

Returns:

  • values – The value(s) to write.

  • spreadsheet_id (str) – The ID of a Google Sheets file.

  • cell (str, optional) – The cell (top-left corner) to start writing the values to. For example, 'C9'.

  • sheet (str, optional) – The name of a sheet in the spreadsheet to write the values to. If not specified and only one sheet exists in the spreadsheet then automatically determines the sheet name; however, it is more efficient to specify the name of the sheet.

  • row_major (bool, optional) – Whether to write the values in row-major or column-major order.

  • raw (bool, optional) – Determines how the values should be interpreted. If True, the values will not be parsed and will be stored as-is. If False, the values will be parsed as if the user typed them into the UI. Numbers will stay as numbers, but strings may be converted to numbers, dates, etc. following the same rules that are applied when entering text into a cell via the Google Sheets UI.

class msl.io.google_api.GoogleAPI(service, version, credentials, scopes, read_only, account)[source]

Bases: object

Base class for all Google APIs.

close()[source]

Close the connection to the API service.

property service

The Resource object with methods for interacting with the API service.

class msl.io.google_api.GValueOption(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Determines how values should be returned.

FORMATTED = 'FORMATTED_VALUE'

Values will be calculated and formatted in the reply according to the cell’s formatting. Formatting is based on the spreadsheet’s locale, not the requesting user’s locale. For example, if A1 is 1.23 and A2 is =A1 and formatted as currency, then A2 would return “$1.23”.

FORMULA = 'FORMULA'

Values will not be calculated. The reply will include the formulas. For example, if A1 is 1.23 and A2 is =A1 and formatted as currency, then A2 would return “=A1”.

UNFORMATTED = 'UNFORMATTED_VALUE'

Values will be calculated, but not formatted in the reply. For example, if A1 is 1.23 and A2 is =A1 and formatted as currency, then A2 would return the number 1.23.

class msl.io.google_api.GDateTimeOption(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Determines how dates should be returned.

FORMATTED_STRING = 'FORMATTED_STRING'

Instructs date, time, datetime, and duration fields to be output as strings in their given number format (which is dependent on the spreadsheet locale).

SERIAL_NUMBER = 'SERIAL_NUMBER'

Instructs date, time, datetime, and duration fields to be output as doubles in “serial number” format, as popularized by Lotus 1-2-3. The whole number portion of the value (left of the decimal) counts the days since December 30th 1899. The fractional portion (right of the decimal) counts the time as a fraction of the day. For example, January 1st 1900 at noon would be 2.5, 2 because it’s 2 days after December 30st 1899, and .5 because noon is half a day. February 1st 1900 at 3pm would be 33.625. This correctly treats the year 1900 as not a leap year.

class msl.io.google_api.GCellType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

The spreadsheet cell data type.

BOOLEAN = 'BOOLEAN'
CURRENCY = 'CURRENCY'
DATE = 'DATE'
DATE_TIME = 'DATE_TIME'
EMPTY = 'EMPTY'
ERROR = 'ERROR'
NUMBER = 'NUMBER'
PERCENT = 'PERCENT'
SCIENTIFIC = 'SCIENTIFIC'
STRING = 'STRING'
TEXT = 'TEXT'
TIME = 'TIME'
UNKNOWN = 'UNKNOWN'
class msl.io.google_api.GCell(value, type, formatted)

Bases: tuple

The information about a Google Sheets cell.

value

The value of the cell.

type

GCellType: The data type of value.

formatted

str: The formatted value (i.e., how the value is displayed in the cell).