onedrive.api module

OneDrive API client.

class onedrive.api.OneDriveAPIClient[source]

Bases: onedrive.auth.OneDriveOAuthClient

OneDrive API client.

assert_dir(path)[source]

Assert that path is an existing directory on OneDrive.

Parameters:

path : str

Path of remote item.

Raises:

onedrive.exceptions.FileNotFoundError

If requested item is not found.

onedrive.exceptions.NotADirectoryError

If requested item exists but is a file.

assert_exists(path)[source]

Assert that path exists on OneDrive.

Parameters:

path : str

Path of remote item.

Raises:

onedrive.exceptions.FileNotFoundError

If requested item is not found.

assert_file(path)[source]

Assert that path is an existing file on OneDrive.

Parameters:

path : str

Path of remote item.

Raises:

onedrive.exceptions.FileNotFoundError

If requested item is not found.

onedrive.exceptions.IsADirectoryError

If requested item exists but is a directory.

children(path)[source]

List children of an item.

Note that no exception is raised when path points to a file; the returned list is empty.

Parameters:

path : str

Path of remote item.

Returns:

children : list

Returns a list of objects as returned by the children API (https://dev.onedrive.com/items/list.htm). If the requested item turns out to be a file, then the return value will be an empty list.

Example return value for the children API (truncated):

[
  {"name": "myfile.jpg", "size": 2048, "file": {} },
  {"name": "Documents", "folder": { "childCount": 4 } },
  {"name": "Photos", "folder": { "childCount": 203 } },
  {"name": "my sheet(1).xlsx", "size": 197 }
]
Raises:

onedrive.exceptions.FileNotFoundError

If the requested item is not found.

copy(*args, **kwargs)[source]

Alias for self.move_or_copy("copy", *args, **kwargs).

Basic usage: copy(path, new_parent, new_name).

download(path, destdir=None, compare_hash=True, show_progress=False, resume=True, downloader=None)[source]

Download a file from OneDrive.

Parameters:

path : str

Remote path of file to download.

destdir : str

Destination directory. Default is None for the current working directory.

compare_hash : bool, optional

Whether to compare local and remote file hashes. Default is True.

show_progress : bool, optional

Whether to display a progress bar. Default is False.

resume : bool, optional

Whether to try to resume an interrupted download. Default is True.

downloader : str, optional

"curl", "wget", or None. If None, use the requests package; otherwise, use the specified external downloader for download (specified downloader has to be on PATH). Default is None.

Raises:

onedrive.exceptions.FileNotFoundError

If the requested file is not found.

onedrive.exceptions.IsADirectoryError

If the requested item is a directory.

FileExistsError

If a file exists locally with the same filename.

onedrive.exceptions.CorruptedDownload

If the download appears corrupted (size or SHA-1 mismatch)

exists(path)[source]

Check if file or directory exists on OneDrive.

Parameters:

path : str

Path of remote item.

Returns:

bool

getmtime(path)[source]

Get the time of last modification of path.

Parameters:

path : str

Path of remote item.

Returns:

posix_time : int

The number of seconds since the epoch.

Raises:

onedrive.exceptions.FileNotFoundError

If the requested item is not found.

getsize(path)[source]

Get the size, in bytes, of path.

This differs from os.path.getsize in that the total size of a directory is returned.

Parameters:

path : str

Path of remote item.

Returns:

size : int

Raises:

onedrive.exceptions.FileNotFoundError

If the requested item is not found.

geturl(path)[source]

Get URL for a file or directory.

Parameters:

path : str

Path of remote item.

Returns:

url : str

Raises:

onedrive.exceptions.FileNotFoundError

If requested item is not found.

isdir(path)[source]

Check if path is an existing directory on OneDrive.

Parameters:

path : str

Path of remote item.

Returns:

bool

isfile(path)[source]

Check if path is an existing file on OneDrive.

Parameters:

path : str

Path of remote item.

Returns:

bool

listdir(path, names_only=False)[source]

List children of a directory.

Get os.listdir behavior (names of children) by setting names_only to True. Otherwise, a list of full metadata objects is returned.

Parameters:

path : str

Path of remote directory.

names_only : bool, optional

List names only. Default is False.

Returns:

list

A list containing metadata objects of all children of the directory given by path. If names_only is set to True, then the list only contains the names of all children.

Raises:

onedrive.exceptions.FileNotFoundError:

If the requested item is not found.

onedrive.exceptions.NotADirectoryError:

If the requested item is not a directory.

makedirs(path, exist_ok=False)[source]

Recursively create directory.

Parameters:

path : str

Path of remote directory to make.

exist_ok : bool

If False, onedrive.exceptions.FileExistsError is raised when path already exists and is a directory. Default is False.

Returns:

metadata : dict

Metadata object of the created (or existing) directory, as returned by a standard metadata request.

Raises:

onedrive.exceptions.FileExistsError

If path already exists and is a directory (with exist_ok set to False).

onedrive.exceptions.NotADirectoryError

If path or one of its intermediate paths exists and is not a directory.

See also

mkdir

metadata(path)[source]

Get metadata of a file or directory.

Parameters:

path : str

Path of remote item.

Returns:

metadata : dict

The JSON object as returned by the API: https://dev.onedrive.com/items/get.htm.

Raises:

onedrive.exceptions.FileNotFoundError

If requested item is not found.

mkdir(path)[source]

Create a directory (no recursive).

Parameters:

path : str

Path of remote directory to make.

Returns:

metadata : dict

Metadata object of the created directory, as returned by a standard metadata request.

Raises:

onedrive.exceptions.FileNotFoundError

If the parent does not exist.

onedrive.exceptions.FileExistsError

If path already exists and is a directory.

onedrive.exceptions.NotADirectoryError

If the parent is not a directory.

See also

makedirs

monitor_copy(monitor_url, monitor_interval=1, show_progress=False, src=None, dst=None)[source]

Monitor an async copy job.

Parameters:

monitor_url : str

A monitor URL returned by the copy API. See https://dev.onedrive.com/items/copy.htm.

monitor_interval : float, optional

Interval between two status queries, in seconds. Default is 1.

show_progress : bool, optional

Whether to print textual progress information to stderr. Default is False.

src, dst : str

Source and destination paths. Used for informational purpose only. Defaults are None.

Raises:

onedrive.exceptions.CopyError

If the copy operation failed or was cancelled.

move(*args, **kwargs)[source]

Alias for self.move_or_copy("move", *args, **kwargs).

Basic usage: move(path, new_parent, new_name).

move_or_copy(action, src, dst, overwrite=False, block=True, monitor_interval=1, show_progress=False)[source]

Move or copy an item.

https://dev.onedrive.com/items/move.htm. https://dev.onedrive.com/items/copy.htm.

Parameters:

action : {“move”, “copy”}

Select an action.

src : str

Source item path.

dst : dst

Destination item path (including both dirname and basename).

overwrite : bool, optional

Whether to overwrite in the case of a conflict. Default is False. Note that even when this is set to True, the destination won’t be overwritten if it is not of the same type as the source (i.e., source is file but dest is directory, or the other way round), or if it is a nonempty directory.

block : bool, optional

Whether to block until copy completes or errors (only useful when action is copy). Default is True.

monitor_interval : float, optional

Only useful when action is copy. See monitor_copy.

show_progress : bool, optional

Only useful when action is copy. See monitor_copy.

Returns:

monitor_url : str

If action is copy and block is set to True, then return the URL for monitoring copy status (which can be passed to monitor_copy); otherwise, return nothing.

Raises:

onedrive.exceptions.FileNotFoundError

If source or the parent of the destination does not exist.

onedrive.exceptions.NotADirectoryError

If the parent of the destination exists but is not a directory.

onedrive.exceptions.FileExistsError

If the source and destination are the same item (whether overwrite or not); or if overwrite is False and the destination item already exists.

onedrive.exceptions.PermissionError

If trying to overwrite a dest with a source of a different type, or trying to overwrite a nonempty directory.

onedrive.excpetions.CopyError

If action is copy, block is True, and the copy operation fails.

See also

monitor_copy, move, copy

remove(path)[source]

Alias for self.rm(path).

removedirs(path)[source]

Remove directories recursively.

Works like rmdir except that, if the leaf directory is successfully removed, removedirs tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty).

Parameters:

path : str

Path of remote directory to remove.

Raises:

See ``rmdir``. Only exceptions on the leaf directory are raised.

rename(src, dst)[source]

Rename the file or directory src to dst.

Parameters:

src, dst : str

Remote paths of source and destination.

Raises:

onedrive.exceptions.FileNotFoundError

If src or the parent directory of dst does not exist.

onedrive.exceptions.FileExistsError

If dst already exists.

renames(src, dst)[source]

Recursive directory or file renaming function.

Works like rename, except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned away using removedirs.

Parameters:

src, dst : str

Remote paths of source and destination.

Raises:

onedrive.exceptions.FileNotFoundError

If src does not exist.

onedrive.exceptions.FileExistsError

If dst already exists.

onedrive.exceptions.NotADirectoryError

If one of the intermediate paths of dst already exists and is not a directory.

rm(path, recursive=False)[source]

Remove an item.

Parameters:

path : str

Path of remote item to remove.

recursive : bool

If True, remove a directory and its children recursively; otherwise, raise onedrive.exceptions.IsADirectoryError when the item requested is a directory. Default is False.

Raises:

onedrive.exceptions.FileNotFoundError

If the item does not exist in the first place.

onedrive.exceptions.IsADirectoryError

If recursive is set to False and the requested item is a directory.

rmdir(path)[source]

Remove an empty directory.

Parameters:

path : str

Path of remote directory to remove.

Raises:

onedrive.exceptions.FileNotFoundError

If the item does not exist in the first place.

onedrive.exceptions.NotADirectoryError

If the item exists but is not a directory.

onedrive.exceptions.PermissionError

If the directory is not empty.

rmtree(path)[source]

Remove directory tree.

Basically an alias for self.rm(path, recursive=True), with the additional check that path is an existing directory.

Parameters:

path : str

Path of remote directory tree to remove.

Raises:

onedrive.exceptions.FileNotFoundError

If the item does not exist in the first place.

onedrive.exceptions.NotADirectoryError

If the item exists but is not a directory.

upload(directory, local_path, **kwargs)[source]

Upload a single file.

If the file is smaller than simple_upload_threshold (default is 100MiB), then it is uploaded via the simple upload API (https://dev.onedrive.com/items/upload_put.htm). Otherwise, it is uploaded via the resumable upload API (https://dev.onedrive.com/items/upload_large_files.htm).

Note that some of the options in “Other Parameters” beblow (passed via **kwargs) only apply to resumable upload.

Parameters:

directory : str

Remote directory to upload to.

local_path : str

Path to the local file to be uploaded.

Other Parameters:
 

conflict_behavior : {“fail”, “replace”, “rename”}, optional

Default is "fail".

simple_upload_threshold : int, optional

Largest file size, in bytes, for using the simple upload API; if the file size exeeds the threshold, then the resumable upload API is used instead. Default is 1048576 (1 MiB). This value should not exceed 104857600 (100 MiB).

compare_hash : bool, optional

Whether to compare the SHA-1 digest of the local file and the uploaded file. Default is True. Note that True is required for resuming upload across CLI sessions (the idea is: without checksumming, the file might be modified or even replaced, so resuming upload is a very bad idea).

check_remote : bool, optional

Whether to check the existence of the remote item before initiating upload. The check can be avoided if the remote item is known to not exist (e.g., because the directory is newly created), thus avoiding overhead. Default is True.

chunk_size : str, optional

Size of each chunk when uploading the file. Default is 10485760 (10 MiB). Only applies to resumable upload.

timeout : int, optional

Timeout for uploading each chunk. Default is 15. Only applies to resumable upload.

stream : bool, optional

Whether to stream each chunk. Default is False. You should only consider setting this to True when memory usage is a serious concern. Only applies to resumable upload (simple upload is always streamed).

show_progress : bool, optional

Whether to print progress information to stderr. Default is False. This option applies to both simple and resumable upload, but for simple upload only a few messages will be printed (as opposed to continuous update) for each file even when show_progress is set to True.

Raises:

FileNotFoundError

If local path does not exist.

IsADirectoryError

If local path exists but is a directory.

onedrive.exceptions.FileExistsError

If conflict behavior is set to "fail", and remote item already exists.

onedrive.exceptions.IsADirectoryError

If conflict behavior is set to "replace" or "rename", but the remote item is an existing directory (hence cannot be replaced or renamed).

onedrive.exceptions.UploadError

Any error causing a failed upload.

walk(top, topdown=True, paths_only=False, **kwargs)[source]

Walk a directory tree.

Retrieve metadata of items (or names only, if you prefer) in a directory tree by walking the tree either top-down or bottom-up. See https://docs.python.org/3/library/os.html#os.walk for more detailed explanation and usage examples (in fact, part of the doc you see here is directly copied from there).

Parameters:

top : str

The path to the root directory.

topdown : bool, optional

If True, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If False, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated. Default is True.

When topdown is True, the caller can modify the dirs or dirnames list in-place, and walk will only recurse into the subdirectories that remain; this can be used to prune the search, impose a specific order of visiting, or even to inform walk about directories the caller creates or renames before it resumes walk again. Modifying the list when topdown is False is ineffective, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated.

paths_only : bool, optional

Whether to yield only the directory path and lists with only item names (as opposed to full metadata objects). See the “Yields” section. Default is False.

Yields:

(dirmetadata, dirs, files) or (dirpath, dirnames, filenames)

For each directory in the tree rooted at directory top (including top itself), a three-tuple is yielded. Whether full metadata objects or only path/names are yielded depends on the paths_only option.

Other Parameters:
 

check_dir : bool, optional

Whether to perform a check to confirm top is an existing directory. If set to False, walk will just assume top is an existing directory, will may lead to surprises if you haven’t confirmed it beforehand. Default is True. This parameter is mostly used internally (to reduce recursion overhead).

metadata : dict, optional

The metadata object of top, if it is already known; default is None. This parameter is used to avoid one extra metadata query when paths_only is False. It becomes significant when used in a recursive setting.

Raises:

onedrive.exceptions.FileNotFoundError

If top is not found.

onedrive.exceptions.IsADirectoryError

If top exists but is a directory.

walkn(top, level=0, topdown=True, paths_only=False, **kwargs)[source]

Walk, armored with level info.

See walk. This method works exactly the same as walk except that the level of the subdirectory is prepended to each yielded tuple. By default top has level 0, but this can be customized via the level option.

Previous topic

onedrive package

Next topic

onedrive.auth module

This Page