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.

class maestral.client.DropboxClient(config_name, timeout=100, session=None)[source]

Bases: object

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, OSErrors from the local file system API and connection errors will be caught and reraised as a subclass of maestral.errors.MaestralApiError.

This class can be used as a context manager to clean up any network resources from the API requests.

Example
>>> from maestral.client import DropboxClient
>>> with DropboxClient("maestral") as client:
...     res = client.list_folder("/")
>>> print(res.entries)
Parameters
  • config_name (str) – Name of config file and state file to use.

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

  • session (Optional[requests.sessions.Session]) – Optional requests session to use. If not given, a new session will be created with dropbox.dropbox_client.create_session().

Return type

None

SDK_VERSION: str = '2.0'
property dbx_base: dropbox.dropbox_client.Dropbox

The underlying Dropbox SDK instance without namespace headers.

property dbx: dropbox.dropbox_client.Dropbox

The underlying Dropbox SDK instance with namespace headers.

property linked: bool

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

Return type

str

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 (str) – OAuth token for Dropbox access.

Returns

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

Return type

int

Unlinks the Dropbox account.

Raises
Return type

None

property account_info: dropbox.users.FullAccount

Returns cached account info. Use get_account_info() to get the latest account info from Dropbox servers.

property namespace_id: str

The namespace ID of the path root currently used by the DropboxClient. All file paths will be interpreted as relative to the root namespace. Use update_path_root() to update the root namespace after the user joins or leaves a team with a Team Space.

property is_team_space: bool

Whether the user’s Dropbox uses a Team Space. Use update_path_root() to update the root namespace after the user joins or eaves a team with a Team Space.

close()[source]

Cleans up all resources like the request session/network connection.

Return type

None

clone(config_name=None, timeout=None, session=None)[source]

Creates a new copy of the Dropbox client with the same defaults unless modified by arguments to clone().

Parameters
  • config_name (Optional[str]) – Name of config file and state file to use.

  • timeout (Optional[float]) – Timeout for individual requests.

  • session (Optional[requests.sessions.Session]) – Requests session to use.

Returns

A new instance of DropboxClient.

Return type

maestral.client.DropboxClient

clone_with_new_session()[source]

Creates a new copy of the Dropbox client with the same defaults but a new requests session.

Returns

A new instance of DropboxClient.

Return type

maestral.client.DropboxClient

update_path_root(root_info=None)[source]

Updates the root path for the Dropbox client. All files paths given as arguments to API calls such as list_folder() or get_metadata() will be interpreted as relative to the root path. All file paths returned by API calls, for instance in file metadata, will be relative to this root path.

The root namespace will change when the user joins or leaves a Dropbox Team with Team Spaces. If this happens, API calls using the old root namespace will raise a PathRootError. Use this method to update to the new root namespace.

See https://developers.dropbox.com/dbx-team-files-guide and https://www.dropbox.com/developers/reference/path-root-header-modes for more information on Dropbox Team namespaces and path root headers in API calls.

Note

We don’t automatically switch root namespaces because API users may want to take action when the path root has changed before making further API calls. Be prepared to handle :class:`PathRootError`s and act accordingly.

Parameters

root_info (Optional[dropbox.common.RootInfo]) – Optional dropbox.common.RootInfo describing the path root. If not given, the latest root info will be fetched from Dropbox servers.

Return type

None

get_account_info(dbid=None)[source]

Gets current account information.

Parameters

dbid (Optional[str]) – Dropbox ID of account. If not given, will get the info of the currently linked account.

Returns

Account info.

Return type

dropbox.users.FullAccount

get_space_usage()[source]
Returns

The space usage of the currently linked account.

Return type

dropbox.users.SpaceUsage

get_metadata(dbx_path, **kwargs)[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 (str) – 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.

Return type

Optional[dropbox.files.Metadata]

list_revisions(dbx_path, mode='path', limit=10)[source]

Lists all file revisions for the given file.

Parameters
  • dbx_path (str) – Path to file on Dropbox.

  • mode (str) – 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 (int) – Maximum number of revisions to list.

Returns

File revision history.

Return type

dropbox.files.ListRevisionsResult

restore(dbx_path, rev)[source]

Restore an old revision of a file.

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

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

Returns

Metadata of restored file.

Return type

dropbox.files.FileMetadata

download(dbx_path, local_path, sync_event=None, **kwargs)[source]

Downloads a file from Dropbox to given local path.

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

  • local_path (str) – Path to local download destination.

  • sync_event (Optional[SyncEvent]) – If given, the sync event will be updated with the number of downloaded bytes.

  • kwargs – Keyword arguments for the Dropbox API files_download endpoint.

Returns

Metadata of downloaded item.

Return type

dropbox.files.FileMetadata

upload(local_path, dbx_path, chunk_size=5000000, sync_event=None, **kwargs)[source]

Uploads local file to Dropbox.

Parameters
  • local_path (str) – Path of local file to upload.

  • dbx_path (str) – Path to save file on Dropbox.

  • kwargs – Keyword arguments for Dropbox SDK files_upload.

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

  • sync_event (Optional[SyncEvent]) – If given, the sync event will be updated with the number of downloaded bytes.

Returns

Metadata of uploaded file.

Return type

dropbox.files.FileMetadata

remove(dbx_path, **kwargs)[source]

Removes a file / folder from Dropbox.

Parameters
  • dbx_path (str) – Path to file on Dropbox.

  • kwargs – Keyword arguments for the Dropbox API files_delete_v2 endpoint.

Returns

Metadata of deleted item.

Return type

dropbox.files.Metadata

remove_batch(entries, batch_size=900)[source]

Deletes multiple items on Dropbox in a batch job.

Parameters
  • entries (List[Tuple[str, str]]) – 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 (int) – 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 SyncErrors for failures. Results will be in the same order as the original input.

Return type

List[Union[dropbox.files.Metadata, maestral.errors.MaestralApiError]]

move(dbx_path, new_path, **kwargs)[source]

Moves / renames files or folders on Dropbox.

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

  • new_path (str) – New path on Dropbox to move to.

  • kwargs – Keyword arguments for the Dropbox API files_move_v2 endpoint.

Returns

Metadata of moved item.

Return type

dropbox.files.Metadata

make_dir(dbx_path, **kwargs)[source]

Creates a folder on Dropbox.

Parameters
  • dbx_path (str) – Path of Dropbox folder.

  • kwargs – Keyword arguments for the Dropbox API files_create_folder_v2 endpoint.

Returns

Metadata of created folder.

Return type

dropbox.files.FolderMetadata

make_dir_batch(dbx_paths, batch_size=900, **kwargs)[source]

Creates multiple folders on Dropbox in a batch job.

Parameters
  • dbx_paths (List[str]) – List of dropbox folder paths.

  • batch_size (int) – 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 the Dropbox API files/create_folder_batch endpoint.

Returns

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

Return type

List[Union[dropbox.files.Metadata, maestral.errors.MaestralApiError]]

share_dir(dbx_path, **kwargs)[source]

Converts a Dropbox folder to a shared folder. Creates the folder if it does not exist.

Parameters
  • dbx_path (str) – Path of Dropbox folder.

  • kwargs – Keyword arguments for the Dropbox API files_create_folder_v2 endpoint.

Returns

Metadata of shared folder.

Return type

dropbox.sharing.SharedFolderMetadata

get_latest_cursor(dbx_path, include_non_downloadable_files=False, **kwargs)[source]

Gets the latest cursor for the given folder and subfolders.

Parameters
  • dbx_path (str) – Path of folder on Dropbox.

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

  • kwargs – Additional keyword arguments for Dropbox API files/list_folder/get_latest_cursor endpoint.

Returns

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

Return type

str

list_folder(dbx_path, max_retries_on_timeout=4, include_non_downloadable_files=False, **kwargs)[source]

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

Parameters
  • dbx_path (str) – Path of folder on Dropbox.

  • max_retries_on_timeout (int) – 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 (bool) – If True, files that cannot be downloaded (at the moment only G-suite files on Dropbox) will be included.

  • kwargs – Additional keyword arguments for Dropbox API files/list_folder endpoint.

Returns

Content of given folder.

Return type

dropbox.files.ListFolderResult

list_folder_iterator(dbx_path, max_retries_on_timeout=4, include_non_downloadable_files=False, **kwargs)[source]

Lists the contents of a folder on Dropbox. Returns an iterator yielding dropbox.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 (str) – Path of folder on Dropbox.

  • max_retries_on_timeout (int) – 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 (bool) – If True, files that cannot be downloaded (at the moment only G-suite files on Dropbox) will be included.

  • kwargs – Additional keyword arguments for the Dropbox API files/list_folder endpoint.

Returns

Iterator over content of given folder.

Return type

Iterator[dropbox.files.ListFolderResult]

wait_for_remote_changes(last_cursor, timeout=40)[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 (str) – Last to cursor to compare for changes.

  • timeout (int) – Seconds to wait until timeout. Must be between 30 and 480. The Dropbox API will add a random jitter of up to 60 sec to this value.

Returns

True if changes are available, False otherwise.

Return type

bool

list_remote_changes(last_cursor)[source]

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

Parameters

last_cursor (str) – Last to cursor to compare for changes.

Returns

Remote changes since given cursor.

Return type

dropbox.files.ListFolderResult

list_remote_changes_iterator(last_cursor)[source]

Lists changes to the remote Dropbox since last_cursor. Returns an iterator yielding dropbox.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 (str) – Last to cursor to compare for changes.

Returns

Iterator over remote changes since given cursor.

Return type

Iterator[dropbox.files.ListFolderResult]

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 (str) – Dropbox path to file or folder to share.

  • visibility (dropbox.sharing.RequestedVisibility) – 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 (Optional[str]) – Password to protect shared link. Is required if visibility is set to password protected and will be ignored otherwise

  • expires (Optional[datetime.datetime]) – Expiry time for shared link. Only available for Professional and Business accounts.

  • kwargs – Additional keyword arguments to create the dropbox.sharing.SharedLinkSettings instance.

Returns

Metadata for shared link.

Return type

dropbox.sharing.SharedLinkMetadata

Revokes a shared link.

Parameters

url (str) – URL to revoke.

Return type

None

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 (Optional[str]) – Dropbox path to file or folder.

Returns

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

Return type

dropbox.sharing.ListSharedLinksResult

static flatten_results(results, attribute_name)[source]

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

Parameters
Returns

Flattened result.

Return type

Union[dropbox.sharing.ListSharedLinksResult, dropbox.files.ListFolderResult]

maestral.client.dropbox_to_maestral_error(exc, dbx_path=None, local_path=None)[source]

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

Parameters
  • exc (Union[dropbox.exceptions.DropboxException, stone.backends.python_rsrc.stone_validators.ValidationError, requests.exceptions.HTTPError]) – Dropbox SDK exception..

  • dbx_path (Optional[str]) – Dropbox path associated with the error.

  • local_path (Optional[str]) – Local path associated with the error.

Returns

Converted exception.

Return type

maestral.errors.MaestralApiError

maestral.client.os_to_maestral_error(exc, dbx_path=None, local_path=None)[source]

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

Parameters
  • exc (OSError) – Original OSError.

  • dbx_path (Optional[str]) – Dropbox path associated with the error.

  • local_path (Optional[str]) – Local path associated with the error.

Returns

Converted exception.

Return type

Union[maestral.errors.MaestralApiError, OSError]

maestral.client.convert_api_errors(dbx_path=None, local_path=None)[source]

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

Parameters
  • dbx_path (Optional[str]) – Dropbox path associated with the error.

  • local_path (Optional[str]) – Local path associated with the error.

Return type

Iterator[None]