Skip to content

net

DownloadSizeExceededError

DownloadSizeExceededError(filesize: int, maxsize: int)

Bases: Exception

Exception raised when a file download exceeds the maximum allowed size.

Attributes:

Name Type Description
filesize int

The actual file size in bytes.

maxsize int

The maximum allowed size in bytes.

Source code in stdl/net.py
def __init__(self, filesize: int, maxsize: int) -> None:
    self.filesize = filesize
    self.maxsize = maxsize

download

download(url: str, path: str, *, maxsize: int | str | None = None, progressbar: bool = False, overwrite: bool = False) -> tuple[str, HTTPMessage]

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,
) -> tuple[str, HTTPMessage]:
    """
    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 and ProgressBarTQDM is not None:
        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:
        if progressbar and ProgressBarTQDM is None:
            warnings.warn(
                "progressbar=True requested but tqdm is not installed; downloading without progress bar.",
                RuntimeWarning,
                stacklevel=2,
            )

        r = urlretrieve(url, path)

    return r