maestral.client =============== .. py:module:: maestral.client .. autoapi-nested-parse:: 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 --------------- .. py:class:: DropboxClient(config_name, cred_storage, timeout = 100, session = None, bandwidth_limit_up = 0, bandwidth_limit_down = 0) 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 :exc:`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) :param config_name: Name of config file and state file to use. :param timeout: Timeout for individual requests. Defaults to 100 sec if not given. :param session: Optional requests session to use. If not given, a new session will be created with :func:`dropbox.dropbox_client.create_session`. :param bandwidth_limit_up: Maximum bandwidth to use for uploads in bytes/sec. Will be enforced over all concurrent uploads (0 = unlimited). :param bandwidth_limit_down: Maximum bandwidth to use for downloads in bytes/sec. Will be enforced over all concurrent downloads (0 = unlimited). .. py:attribute:: SDK_VERSION :type: str :value: '2.0' .. py:attribute:: MAX_TRANSFER_RETRIES :value: 10 .. py:attribute:: MAX_LIST_FOLDER_RETRIES :value: 3 .. py:attribute:: UPLOAD_REQUEST_CHUNK_SIZE :value: 4194304 .. py:attribute:: DATA_TRANSFER_MIN_SLEEP_TIME :value: 0.0001 .. py:property:: dbx_base :type: _DropboxSDK The underlying Dropbox SDK instance without namespace headers. .. py:property:: dbx :type: _DropboxSDK The underlying Dropbox SDK instance with namespace headers. .. py:property:: linked :type: 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. .. py:method:: get_auth_url() Returns a URL to authorize access to a Dropbox account. To link a Dropbox account, retrieve an authorization code from the URL and link Maestral by calling :meth:`link` with the provided code. :returns: URL to retrieve an authorization code. .. py:method:: link(code = None, refresh_token = None, access_token = None) Links Maestral with a Dropbox account using the given authorization code. The code will be exchanged for an access token and a refresh token with Dropbox servers. The refresh token will be stored for future usage in the provided credential store. :param code: Authorization code. :param refresh_token: Optionally, instead of an authorization code, directly provide a refresh token. :param access_token: Optionally, instead of an authorization code or a refresh token, directly provide an access token. Note that access tokens are short-lived. :returns: 0 on success, 1 for an invalid token and 2 for connection errors. .. py:method:: unlink() Unlinks the Dropbox account. The password will be deleted from the provided credential storage. :raises KeyringAccessError: if keyring access fails. :raises DropboxAuthError: if we cannot authenticate with Dropbox. .. py:property:: account_info :type: maestral.core.FullAccount Returns cached account info. Use :meth:`get_account_info` to get the latest account info from Dropbox servers. .. py:property:: namespace_id :type: 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 :meth:`update_path_root` to update the root namespace after the user joins or leaves a team with a Team Space. .. py:property:: is_team_space :type: bool Whether the user's Dropbox uses a Team Space. Use :meth:`update_path_root` to update the root namespace after the user joins or eaves a team with a Team Space. .. py:method:: close() Cleans up all resources like the request session/network connection. .. py:method:: update_path_root(root_info) Updates the root path for the Dropbox client. All files paths given as arguments to API calls such as :meth:`list_folder` or :meth:`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 :exc:`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 :exc:`maestral.exceptions.PathRootError` and act accordingly for all methods. :param root_info: :class:`core.RootInfo` describing the path root. Use :meth:`get_account_info` to retrieve. .. py:method:: get_account_info(dbid: None = None) -> maestral.core.FullAccount get_account_info(dbid: str) -> maestral.core.Account Gets current account information. :param dbid: Dropbox ID of account. If not given, will get the info of the currently linked account. :returns: Account info. .. py:method:: get_space_usage() :returns: The space usage of the currently linked account. .. py:method:: get_metadata(dbx_path, include_deleted = False) 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. :param dbx_path: Path of folder on Dropbox. :param include_deleted: Whether to return data for deleted items. :returns: Metadata of item at the given path or ``None`` if item cannot be found. .. py:method:: list_revisions(dbx_path, mode = 'path', limit = 10) Lists all file revisions for the given file. :param dbx_path: Path to file on Dropbox. :param 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. :param limit: Maximum number of revisions to list. :returns: File revision history. .. py:method:: restore(dbx_path, rev) Restore an old revision of a file. :param dbx_path: The path to save the restored file. :param rev: The revision to restore. Old revisions can be listed with :meth:`list_revisions`. :returns: Metadata of restored file. .. py:method:: download(dbx_path, local_path, sync_event = None) Downloads a file from Dropbox to given local path. :param dbx_path: Path to file on Dropbox or rev number. :param local_path: Path to local download destination. :param sync_event: If given, the sync event will be updated with the number of downloaded bytes. :returns: Metadata of downloaded item. :raises DataCorruptionError: if data is corrupted during download. .. py:method:: upload(local_path, dbx_path, write_mode = WriteMode.Add, update_rev = None, autorename = False, sync_event = None) Uploads local file to Dropbox. If the file size is smaller than 4 MB, the file will be uploaded all at once. Otherwise, the file will be loaded into memory and uploaded in chunks of 4 MB. If the file is modified during this chunked upload, this will raise a :exc:`DataChangedError`. :param local_path: Path of local file to upload. :param dbx_path: Path to save file on Dropbox. :param write_mode: 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. :class:`core.WriteMode.Add` Do not overwrite an existing file if there is a conflict. The autorename strategy is to append a number to the file name. For example, "document.txt" might become "document (2).txt". :class:`core.WriteMode.Overwrite` Always overwrite the existing file. The autorename strategy is the same as it is for ``add``. :class:`core.WriteMode.Update` Overwrite if the given "update_rev" matches the existing file's "rev". The supplied value should be the latest known "rev" of the file, for example, from :class:`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". :param update_rev: Rev to match for :class:`core.WriteMode.Update`. :param sync_event: If given, the sync event will be updated with the number of downloaded bytes. :param autorename: 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. :raises DataChangedError: if the file is modified during a chunked upload. .. py:method:: remove(dbx_path, parent_rev = None) Removes a file / folder from Dropbox. :param dbx_path: Path to file on Dropbox. :param parent_rev: Perform delete if given "rev" matches the existing file's latest "rev". This field does not support deleting a folder. :returns: Metadata of deleted item. .. py:method:: remove_batch(entries, batch_size = 900) Deletes multiple items on Dropbox in a batch job. :param 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. :param 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 SyncErrors for failures. Results will be in the same order as the original input. .. py:method:: move(dbx_path, new_path, autorename = False) Moves / renames files or folders on Dropbox. :param dbx_path: Path to file/folder on Dropbox. :param new_path: New path on Dropbox to move to. :param autorename: Have the Dropbox server try to rename the item in case of a conflict. :returns: Metadata of moved item. .. py:method:: make_dir(dbx_path, autorename = False) Creates a folder on Dropbox. :param dbx_path: Path of Dropbox folder. :param autorename: Have the Dropbox server try to rename the item in case of a conflict. :returns: Metadata of created folder. .. py:method:: make_dir_batch(dbx_paths, batch_size = 900, autorename = False, force_async = False) Creates multiple folders on Dropbox in a batch job. :param dbx_paths: List of dropbox folder paths. :param 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. :param autorename: Have the Dropbox server try to rename the item in case of a conflict. :param force_async: 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. .. py:method:: share_dir(dbx_path, force_async = False) 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. :param dbx_path: Path of Dropbox folder. :param force_async: Whether to force async creation of the Dropbox directory. This only changes implementation details and is currently used to reliably test the async route. :returns: Metadata of shared folder. .. py:method:: get_latest_cursor(dbx_path, include_non_downloadable_files = False) Gets the latest cursor for the given folder and subfolders. :param dbx_path: Path of folder on Dropbox. :param include_non_downloadable_files: If ``True``, files that cannot be downloaded (at the moment only G-suite files on Dropbox) will be included. :param 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. .. py:method:: list_folder(dbx_path, recursive = False, include_deleted = False, include_mounted_folders = True, include_non_downloadable_files = False) Lists the contents of a folder on Dropbox. Similar to :meth:`list_folder_iterator` but returns all entries in a single :class:`core.ListFolderResult` instance. :param dbx_path: Path of folder on Dropbox. :param dbx_path: Path of folder on Dropbox. :param recursive: If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders. :param include_deleted: If true, the results will include entries for files and folders that used to exist but were deleted. :param bool include_mounted_folders: If true, the results will include entries under mounted folders which includes app folder, shared folder and team folder. :param bool include_non_downloadable_files: If true, include files that are not downloadable, i.e. Google Docs. :returns: Content of given folder. .. py:method:: list_folder_iterator(dbx_path, recursive = False, include_deleted = False, include_mounted_folders = True, limit = None, include_non_downloadable_files = False) Lists the contents of a folder on Dropbox. Returns an iterator yielding :class:`core.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. :param dbx_path: Path of folder on Dropbox. :param recursive: If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders. :param include_deleted: If true, the results will include entries for files and folders that used to exist but were deleted. :param bool include_mounted_folders: If true, the results will include entries under mounted folders which includes app folder, shared folder and team folder. :param Nullable[int] limit: 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. :param bool include_non_downloadable_files: If true, include files that are not downloadable, i.e. Google Docs. :returns: Iterator over content of given folder. .. py:method:: wait_for_remote_changes(last_cursor, timeout = 40) Waits for remote changes since ``last_cursor``. Call this method after starting the Dropbox client and periodically to get the latest updates. :param last_cursor: Last to cursor to compare for changes. :param timeout: 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. .. py:method:: list_remote_changes(last_cursor) Lists changes to remote Dropbox since ``last_cursor``. Same as :meth:`list_remote_changes_iterator` but fetches all changes first and returns a single :class:`core.ListFolderResult`. This may be useful if you want to fetch all changes in advance before starting to process them. :param last_cursor: Last to cursor to compare for changes. :returns: Remote changes since given cursor. .. py:method:: list_remote_changes_iterator(last_cursor) Lists changes to the remote Dropbox since ``last_cursor``. Returns an iterator yielding :class:`core.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 :meth:`wait_for_remote_changes` returns ``True``. :param last_cursor: Last to cursor to compare for changes. :returns: Iterator over remote changes since given cursor. .. py:method:: create_shared_link(dbx_path, visibility = LinkAudience.Public, access_level = LinkAccessLevel.Viewer, allow_download = None, password = None, expires = None) 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. :param dbx_path: Dropbox path to file or folder to share. :param visibility: 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. :param access_level: The level of access granted with the link. Can be viewer, editor, or max for maximum possible access level. :param allow_download: Whether to allow download capabilities for the link. :param password: If given, enables password protection for the link. :param expires: 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. .. py:method:: revoke_shared_link(url) Revokes a shared link. :param url: URL to revoke. .. py:method:: list_shared_links(dbx_path = 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. :param 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. .. py:method:: flatten_results(results) :staticmethod: Flattens a sequence listing results from a pagination to a single result with the cursor of the last result in the list. :param results: List of results to flatten. :returns: Flattened result.