maestral.client

This modules contains the Dropbox API client. It wraps calls to the Dropbox Python SDK and handles exceptions, chunked uploads or downloads, etc.

Module Contents

maestral.client.CONNECTION_ERRORS[source]
maestral.client.convert_api_errors(dbx_path: Optional[str] = None, local_path: Optional[str] = None) → Iterator[None][source]

A context manager that catches and re-raises instances of OSError and exceptions.DropboxException as errors.MaestralApiError or ConnectionError.

class maestral.client.DropboxClient(config_name: str, timeout: float = 100)[source]

Client for the Dropbox SDK

This client defines basic methods to wrap Dropbox Python SDK calls, such as creating, moving, modifying and deleting files and folders on Dropbox and downloading files from Dropbox.

All Dropbox SDK exceptions and OSError instances if related to accessing or saving local files will be caught and reraised as a errors.MaestralApiError. Connection errors from requests will be caught and reraised as ConnectionError.

Parameters
  • config_name – Name of config file and state file to use.

  • timeout – Timeout for individual requests. Defaults to 100 sec if not given.

SDK_VERSION :str = 2.0[source]
property dbx(self) → dropbox.Dropbox[source]

The actual Python Dropbox SDK

property linked(self)bool[source]

Indicates if the client is linked to a Dropbox account (read only). This will block until the user’s keyring is unlocked to load the saved auth token.

Raises

KeyringAccessError – if keyring access fails.

get_auth_url(self)str[source]

Returns a URL to authorize access to a Dropbox account. To link a Dropbox account, retrieve an auth token from the URL and link Maestral by calling link() with the provided token.

Returns

URL to retrieve an OAuth token.

Links Maestral with a Dropbox account using the given access token. The token will be stored for future usage as documented in the oauth module.

Parameters

token – OAuth token for Dropbox access.

Returns

0 on success, 1 for an invalid token and 2 for connection errors.

Unlinks the Dropbox account.

Raises
property account_id(self) → Optional[str][source]

The unique Dropbox ID of the linked account

get_account_info(self, dbid: Optional[str] = None)dropbox.users.FullAccount[source]

Gets current account information.

Parameters

dbid – Dropbox ID of account. If not given, will get the info of the currently linked account.

Returns

Account info.

get_space_usage(self) → maestral.client.SpaceUsage[source]
Returns

The space usage of the currently linked account.

get_metadata(self, dbx_path: str, **kwargs) → Optional[files.Metadata][source]

Gets metadata for an item on Dropbox or returns False if no metadata is available. Keyword arguments are passed on to Dropbox SDK files_get_metadata call.

Parameters
  • dbx_path – Path of folder on Dropbox.

  • kwargs – Keyword arguments for Dropbox SDK files_get_metadata.

Returns

Metadata of item at the given path or None if item cannot be found.

list_revisions(self, dbx_path: str, mode: str = 'path', limit: int = 10)dropbox.files.ListRevisionsResult[source]

Lists all file revisions for the given file.

Parameters
  • dbx_path – Path to file on Dropbox.

  • mode – Must be ‘path’ or ‘id’. If ‘id’, specify the Dropbox file ID instead of the file path to get revisions across move and rename events.

  • limit – Maximum number of revisions to list. Defaults to 10.

Returns

File revision history.

restore(self, dbx_path: str, rev: str)dropbox.files.FileMetadata[source]

Restore an old revision of a file.

Parameters
  • dbx_path – The path to save the restored file.

  • rev – The revision to restore. Old revisions can be listed with list_revisions().

Returns

Metadata of restored file.

download(self, dbx_path: str, local_path: str, sync_event: Optional[‘SyncEvent’] = None, **kwargs)dropbox.files.FileMetadata[source]

Downloads file from Dropbox to our local folder.

Parameters
  • dbx_path – Path to file on Dropbox or rev number.

  • local_path – Path to local download destination.

  • sync_event – If given, the sync event will be updated with the number of downloaded bytes.

  • kwargs – Keyword arguments for Dropbox SDK files_download.

Returns

Metadata of downloaded item.

upload(self, local_path: str, dbx_path: str, chunk_size: int = 5 * 10 ** 6, sync_event: Optional[‘SyncEvent’] = None, **kwargs)dropbox.files.FileMetadata[source]

Uploads local file to Dropbox.

Parameters
  • local_path – Path of local file to upload.

  • dbx_path – Path to save file on Dropbox.

  • kwargs – Keyword arguments for Dropbox SDK files_upload.

  • chunk_size – Maximum size for individual uploads. If larger than 150 MB, it will be set to 150 MB.

  • sync_event – If given, the sync event will be updated with the number of downloaded bytes.

Returns

Metadata of uploaded file.

remove(self, dbx_path: str, **kwargs)dropbox.files.Metadata[source]

Removes a file / folder from Dropbox.

Parameters
  • dbx_path – Path to file on Dropbox.

  • kwargs – Keyword arguments for Dropbox SDK files_delete_v2.

Returns

Metadata of deleted item.

remove_batch(self, entries: List[Tuple[str, str]], batch_size: int = 900) → List[Union[files.Metadata, MaestralApiError]][source]

Delete multiple items on Dropbox in a batch job.

Parameters
  • entries – List of Dropbox paths and “rev”s to delete. If a “rev” is not None, the file will only be deleted if it matches the rev on Dropbox. This is not supported when deleting a folder.

  • batch_size – Number of items to delete in each batch. Dropbox allows batches of up to 1,000 items. Larger values will be capped automatically.

Returns

List of Metadata for deleted items or errors.SyncError for failures. Results will be in the same order as the original input.

move(self, dbx_path: str, new_path: str, **kwargs)dropbox.files.Metadata[source]

Moves / renames files or folders on Dropbox.

Parameters
  • dbx_path – Path to file/folder on Dropbox.

  • new_path – New path on Dropbox to move to.

  • kwargs – Keyword arguments for Dropbox SDK files_move_v2.

Returns

Metadata of moved item.

make_dir(self, dbx_path: str, **kwargs)dropbox.files.FolderMetadata[source]

Creates a folder on Dropbox.

Parameters
  • dbx_path – Path of Dropbox folder.

  • kwargs – Keyword arguments for Dropbox SDK files_create_folder_v2.

Returns

Metadata of created folder.

make_dir_batch(self, dbx_paths: List[str], batch_size: int = 900, **kwargs) → List[Union[files.Metadata, MaestralApiError]][source]

Creates multiple folders on Dropbox in a batch job.

Parameters
  • dbx_paths – List of dropbox folder paths.

  • batch_size – Number of folders to create in each batch. Dropbox allows batches of up to 1,000 folders. Larger values will be capped automatically.

  • kwargs – Keyword arguments for Dropbox SDK files_create_folder_batch.

Returns

List of Metadata for created folders or SyncError for failures. Entries will be in the same order as given paths.

get_latest_cursor(self, dbx_path: str, include_non_downloadable_files: bool = False, **kwargs)str[source]

Gets the latest cursor for the given folder and subfolders.

Parameters
  • dbx_path – Path of folder on Dropbox.

  • include_non_downloadable_files – If True, files that cannot be downloaded (at the moment only G-suite files on Dropbox) will be included.

  • kwargs – Other keyword arguments for Dropbox SDK files_list_folder.

Returns

The latest cursor representing a state of a folder and its subfolders.

list_folder(self, dbx_path: str, max_retries_on_timeout: int = 4, include_non_downloadable_files: bool = False, **kwargs)dropbox.files.ListFolderResult[source]

Lists the contents of a folder on Dropbox. Similar to list_folder_iterator() but returns all entries in a single files.ListFolderResult instance.

Parameters
  • dbx_path – Path of folder on Dropbox.

  • max_retries_on_timeout – Number of times to try again if Dropbox servers do not respond within the timeout. Occasional timeouts may occur for very large Dropbox folders.

  • include_non_downloadable_files – If True, files that cannot be downloaded (at the moment only G-suite files on Dropbox) will be included.

  • kwargs – Other keyword arguments for Dropbox SDK files_list_folder.

Returns

Content of given folder.

list_folder_iterator(self, dbx_path: str, max_retries_on_timeout: int = 4, include_non_downloadable_files: bool = False, **kwargs) → Iterator[files.ListFolderResult][source]

Lists the contents of a folder on Dropbox. Returns an iterator yielding files.ListFolderResult instances. The number of entries returned in each iteration corresponds to the number of entries returned by a single Dropbox API call and will be typically around 500.

Parameters
  • dbx_path – Path of folder on Dropbox.

  • max_retries_on_timeout – Number of times to try again if Dropbox servers do not respond within the timeout. Occasional timeouts may occur for very large Dropbox folders.

  • include_non_downloadable_files – If True, files that cannot be downloaded (at the moment only G-suite files on Dropbox) will be included.

  • kwargs – Other keyword arguments for Dropbox SDK files_list_folder.

Returns

Iterator over content of given folder.

wait_for_remote_changes(self, last_cursor: str, timeout: int = 40)bool[source]

Waits for remote changes since last_cursor. Call this method after starting the Dropbox client and periodically to get the latest updates.

Parameters
  • last_cursor – Last to cursor to compare for changes.

  • timeout – Seconds to wait until timeout. Must be between 30 and 480.

Returns

True if changes are available, False otherwise.

list_remote_changes(self, last_cursor: str)dropbox.files.ListFolderResult[source]

Lists changes to remote Dropbox since last_cursor. Same as list_remote_changes_iterator() but fetches all changes first and returns a single files.ListFolderResult. This may be useful if you want to fetch all changes before starting to process them.

Parameters

last_cursor – Last to cursor to compare for changes.

Returns

Remote changes since given cursor.

list_remote_changes_iterator(self, last_cursor: str) → Iterator[files.ListFolderResult][source]

Lists changes to the remote Dropbox since last_cursor. Returns an iterator yielding files.ListFolderResult instances. The number of entries returned in each iteration corresponds to the number of entries returned by a single Dropbox API call and will be typically around 500.

Call this after wait_for_remote_changes() returns True.

Parameters

last_cursor – Last to cursor to compare for changes.

Returns

Iterator over remote changes since given cursor.

Creates a shared link for the given path. Some options are only available for Professional and Business accounts. Note that the requested visibility as access level for the link may not be granted, depending on the Dropbox folder or team settings. Check the returned link metadata to verify the visibility and access level.

Parameters
  • dbx_path – Dropbox path to file or folder to share.

  • visibility – The visibility of the shared link. Can be public, team-only, or password protected. In case of the latter, the password argument must be given. Only available for Professional and Business accounts.

  • password – Password to protect shared link. Is required if visibility is set to password protected and will be ignored otherwise

  • expires – Expiry time for shared link. Only available for Professional and Business accounts.

  • kwargs – Additional keyword arguments for the dropbox.sharing.SharedLinkSettings.

Returns

Metadata for shared link.

Revokes a shared link.

Parameters

url – URL to revoke.

Lists all shared links for a given Dropbox path (file or folder). If no path is given, list all shared links for the account, up to a maximum of 1,000 links.

Parameters

dbx_path – Dropbox path to file or folder.

Returns

Shared links for a path, including any shared links for parents through which this path is accessible.

static flatten_results(results: List[PaginationResultType], attribute_name: str) → PaginationResultType[source]

Flattens a list of Dropbox API results from a pagination to a single result with the cursor of the last entry in the list.

Parameters
  • results – List of :results to flatten.

  • attribute_name – Name of attribute to flatten.

Returns

Flattened result.

maestral.client.os_to_maestral_error(exc: OSError, dbx_path: Optional[str] = None, local_path: Optional[str] = None) → LocalError[source]

Converts a OSError to a MaestralApiError and tries to add a reasonably informative error title and message.

Note

The following exception types should not typically be raised during syncing:

  • InterruptedError: The client will automatically retry on interrupted connections.

  • NotADirectoryError: If raised, this is likely a bug.

  • IsADirectoryError: If raised, this is likely a bug.

Parameters
  • exc – Python Exception.

  • dbx_path – Dropbox path of file which triggered the error.

  • local_path – Local path of file which triggered the error.

Returns

MaestralApiError instance or OSError instance.

maestral.client.dropbox_to_maestral_error(exc: dropbox.exceptions.DropboxException, dbx_path: Optional[str] = None, local_path: Optional[str] = None)maestral.errors.MaestralApiError[source]

Converts a Dropbox SDK exception to a MaestralApiError and tries to add a reasonably informative error title and message.

Parameters
  • excdropbox.exceptions.DropboxException instance.

  • dbx_path – Dropbox path of file which triggered the error.

  • local_path – Local path of file which triggered the error.

Returns

MaestralApiError instance.