Skip to content

net

download

download(url: str, path: str, *, maxsize: int | str | None = None, progressbar: bool = False, overwrite: bool = False)

Download a file

Parameters:

Name Type Description Default
url str

File URL

required
path str

Save path

required
maxsize int | str | None

Maximum file size in bytes or human readable format.

None
progressbar bool

Display progress bar in console.

False
overwrite bool

Overwrite destination path if it already exists.

False

Raises:

Type Description
FileExistsError

if path already exists and overwrite is set to False

DownloadSizeExceededError

if file size exceeds maxsize

Source code in stdl/net.py
def download(
    url: str,
    path: str,
    *,
    maxsize: int | str | None = None,
    progressbar: bool = False,
    overwrite: bool = False,
):
    """
    Download a file

    Args:
        url (str): File URL
        path (str): Save path
        maxsize (int | str | None, optional): Maximum file size in bytes or human readable format.
        progressbar (bool, optional): Display progress bar in console.
        overwrite (bool, optional): Overwrite destination path if it already exists.

    Raises:
        FileExistsError: if path already exists and overwrite is set to False
        DownloadSizeExceededError: if file size exceeds maxsize
    """
    if maxsize is not None:
        if isinstance(maxsize, str):
            maxsize = readable_size_to_bytes(maxsize)
        filesize = int(urlopen(url).headers.get("Content-Length", 0))
        if filesize > maxsize:
            raise DownloadSizeExceededError(filesize, maxsize)

    if os.path.exists(path) and not overwrite:
        raise FileExistsError(path)

    if progressbar:
        with ProgressBarTQDM(unit="B", unit_scale=True, unit_divisor=1024) as t:
            r = urlretrieve(url, path, reporthook=t.update_to, data=None)
        t.total = t.n
    else:
        r = urlretrieve(url, path)
    return r