maestral.client
This module contains the Dropbox API client. It wraps calls to the Dropbox Python SDK and handles exceptions, chunked uploads or downloads, etc.
Module Contents
- class maestral.client.DropboxClient(config_name, timeout=100, session=None)[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, OSErrors from the local file system API and connection errors will be caught and reraised as a subclass of
maestral.exceptions.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 (requests.Session | None) – Optional requests session to use. If not given, a new session will be created with
dropbox.dropbox_client.create_session()
.
- property dbx_base(self)[source]
The underlying Dropbox SDK instance without namespace headers.
- Return type
dropbox.Dropbox
- property dbx(self)[source]
The underlying Dropbox SDK instance with namespace headers.
- Return type
dropbox.Dropbox
- property linked(self)[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.
- Return type
- get_auth_url(self)[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
- link(self, token)[source]
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.
- unlink(self)[source]
Unlinks the Dropbox account.
- Raises
KeyringAccessError – if keyring access fails.
DropboxAuthError – if we cannot authenticate with Dropbox.
- Return type
None
- property account_info(self)[source]
Returns cached account info. Use
get_account_info()
to get the latest account info from Dropbox servers.- Return type
- property namespace_id(self)[source]
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.- Return type
- property is_team_space(self)[source]
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.- Return type
- close(self)[source]
Cleans up all resources like the request session/network connection.
- Return type
None
- clone(self, 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 (str | None) – Name of config file and state file to use.
timeout (float | None) – Timeout for individual requests.
session (requests.Session | None) – Requests session to use.
- Returns
A new instance of DropboxClient.
- Return type
- clone_with_new_session(self)[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
- update_path_root(self, 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()
orget_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
maestral.exceptions.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
maestral.exceptions.PathRootError
and act accordingly for all methods.- Parameters
root_info (RootInfo | None) – 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(self, dbid: None = None) maestral.core.FullAccount [source]
- get_account_info(self, dbid: str) maestral.core.Account
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_metadata(self, dbx_path, include_deleted=False)[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.
- list_revisions(self, dbx_path, mode='path', limit=10)[source]
Lists all file revisions for the given file.
- Parameters
- Returns
File revision history.
- Return type
- restore(self, 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
- download(self, dbx_path, local_path, sync_event=None)[source]
Downloads a file from Dropbox to given local path.
- Parameters
- Returns
Metadata of downloaded item.
- Raises
DataCorruptionError – if data is corrupted during download.
- Return type
- upload(self, local_path, dbx_path, chunk_size=5 * 10 ** 6, write_mode=WriteMode.Add, update_rev=None, autorename=False, sync_event=None)[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.
chunk_size (int) – Maximum size for individual uploads. If larger than 150 MB, it will be set to 150 MB.
write_mode (maestral.core.WriteMode) –
Your intent when writing a file to some path. This is used to determine what constitutes a conflict and what the autorename strategy is. This is used to determine what constitutes a conflict and what the autorename strategy is. In some situations, the conflict behavior is identical: (a) If the target path doesn’t refer to anything, the file is always written; no conflict. (b) If the target path refers to a folder, it’s always a conflict. (c) If the target path refers to a file with identical contents, nothing gets written; no conflict. The conflict checking differs in the case where there’s a file at the target path with contents different from the contents you’re trying to write.
core.WriteMode.Add
Do not overwrite an existing file if there is aconflict. The autorename strategy is to append a number to the file name. For example, “document.txt” might become “document (2).txt”.
core.WriteMode.Overwrite
Always overwrite the existing file. Theautorename strategy is the same as it is for
add
.core.WriteMode.Update
Overwrite if the given “update_rev” matches theexisting file’s “rev”. The supplied value should be the latest known “rev” of the file, for example, from
core.FileMetadata
, from when the file was last downloaded by the app. This will cause the file on the Dropbox servers to be overwritten if the given “rev” matches the existing file’s current “rev” on the Dropbox servers. The autorename strategy is to append the string “conflicted copy” to the file name. For example, “document.txt” might become “document (conflicted copy).txt” or “document (Panda’s conflicted copy).txt”.
update_rev (str | None) – Rev to match for
core.WriteMode.Update
.sync_event (SyncEvent | None) – If given, the sync event will be updated with the number of downloaded bytes.
autorename (bool) – If there’s a conflict, as determined by
mode
, have the Dropbox server try to autorename the file to avoid conflict. The default for this field is False.
- Returns
Metadata of uploaded file.
- Raises
DataCorruptionError – if data is corrupted during upload.
- Return type
- remove(self, dbx_path, parent_rev=None)[source]
Removes a file / folder from Dropbox.
- Parameters
- Returns
Metadata of deleted item.
- Return type
- remove_batch(self, entries, batch_size=900)[source]
Deletes multiple items on Dropbox in a batch job.
- Parameters
entries (Sequence[tuple[str, str | None]]) – 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
- move(self, dbx_path, new_path, autorename=False)[source]
Moves / renames files or folders on Dropbox.
- Parameters
- Returns
Metadata of moved item.
- Return type
- make_dir(self, dbx_path, autorename=False)[source]
Creates a folder on Dropbox.
- Parameters
- Returns
Metadata of created folder.
- Return type
- make_dir_batch(self, dbx_paths, batch_size=900, autorename=False, force_async=False)[source]
Creates multiple folders on Dropbox in a batch job.
- Parameters
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.
autorename (bool) – Have the Dropbox server try to rename the item in case of a conflict.
force_async (bool) – Whether to force asynchronous creation on Dropbox servers.
- Returns
List of Metadata for created folders or SyncError for failures. Entries will be in the same order as given paths.
- Return type
Converts a Dropbox folder to a shared folder. Creates the folder if it does not exist. May return None if the folder is immediately deleted after creation.
- Parameters
dbx_path (str) – Path of Dropbox folder.
kwargs – Keyword arguments for the Dropbox API sharing/share_folder endpoint.
- Returns
Metadata of shared folder.
- Return type
FolderMetadata | None
- get_latest_cursor(self, dbx_path, include_non_downloadable_files=False, **kwargs)[source]
Gets the latest cursor for the given folder and subfolders.
- Parameters
- Returns
The latest cursor representing a state of a folder and its subfolders.
- Return type
- list_folder(self, dbx_path, recursive=False, include_deleted=False, include_mounted_folders=True, include_non_downloadable_files=False)[source]
Lists the contents of a folder on Dropbox. Similar to
list_folder_iterator()
but returns all entries in a singledropbox.files.ListFolderResult
instance.- Parameters
dbx_path (str) – Path of folder on Dropbox.
dbx_path – Path of folder on Dropbox.
recursive (bool) – If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders.
include_deleted (bool) – If true, the results will include entries for files and folders that used to exist but were deleted.
include_mounted_folders (bool) – If true, the results will include entries under mounted folders which includes app folder, shared folder and team folder.
include_non_downloadable_files (bool) – If true, include files that are not downloadable, i.e. Google Docs.
- Returns
Content of given folder.
- Return type
- list_folder_iterator(self, dbx_path, recursive=False, include_deleted=False, include_mounted_folders=True, limit=None, include_non_downloadable_files=False)[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.
recursive (bool) – If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders.
include_deleted (bool) – If true, the results will include entries for files and folders that used to exist but were deleted.
include_mounted_folders (bool) – If true, the results will include entries under mounted folders which includes app folder, shared folder and team folder.
limit (Nullable[int]) – The maximum number of results to return per request. Note: This is an approximate number and there can be slightly more entries returned in some cases.
include_non_downloadable_files (bool) – If true, include files that are not downloadable, i.e. Google Docs.
- Returns
Iterator over content of given folder.
- Return type
Iterator[maestral.core.ListFolderResult]
- wait_for_remote_changes(self, 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.
- list_remote_changes(self, last_cursor)[source]
Lists changes to remote Dropbox since
last_cursor
. Same aslist_remote_changes_iterator()
but fetches all changes first and returns a singledropbox.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
- list_remote_changes_iterator(self, last_cursor)[source]
Lists changes to the remote Dropbox since
last_cursor
. Returns an iterator yieldingdropbox.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()
returnsTrue
.- Parameters
last_cursor (str) – Last to cursor to compare for changes.
- Returns
Iterator over remote changes since given cursor.
- Return type
Iterator[maestral.core.ListFolderResult]
Creates a shared link for the given path. Some options are only available for Professional and Business accounts. Note that the requested visibility and 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 (maestral.core.LinkAudience) – The visibility of the shared link. Can be public, team-only, or no-one. In case of the latter, the link merely points the user to the content and does not grant additional rights to the user. Users of this link can only access the content with their pre-existing access rights.
access_level (maestral.core.LinkAccessLevel) – The level of access granted with the link. Can be viewer, editor, or max for maximum possible access level.
allow_download (bool | None) – Whether to allow download capabilities for the link.
password (str | None) – If given, enables password protection for the link.
expires (datetime | None) – Expiry time for shared link. If no timezone is given, assume UTC. May not be supported for all account types.
- Returns
Metadata for shared link.
- Return type
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 (str | None) – 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