Skip to content

utils

django_spire.file.utils

SIZE_BYTES_PER_KB = 1024 module-attribute

SIZE_BYTES_PER_MB = 1048576 module-attribute

SIZE_BYTES_PER_GB = 1073741824 module-attribute

SIZE_BYTES_PER_TB = 1099511627776 module-attribute

random_64_char_token

Source code in django_spire/file/utils.py
def random_64_char_token() -> str:
    return binascii.hexlify(os.urandom(32)).decode()

parse_name

Source code in django_spire/file/utils.py
def parse_name(filename: str) -> str:
    if not filename:
        return ''

    return PurePosixPath(filename).stem

parse_extension

Source code in django_spire/file/utils.py
def parse_extension(filename: str) -> str:
    if not filename:
        return ''

    return PurePosixPath(filename).suffix.lstrip('.').lower()

format_size

Source code in django_spire/file/utils.py
def format_size(size_bytes: int) -> str:
    if size_bytes <= 0:
        return '0 KB'

    if size_bytes < SIZE_BYTES_PER_MB:
        return f'{round(size_bytes / SIZE_BYTES_PER_KB, 2)} KB'

    if size_bytes < SIZE_BYTES_PER_GB:
        return f'{round(size_bytes / SIZE_BYTES_PER_MB, 2)} MB'

    if size_bytes < SIZE_BYTES_PER_TB:
        return f'{round(size_bytes / SIZE_BYTES_PER_GB, 2)} GB'

    return f'{round(size_bytes / SIZE_BYTES_PER_TB, 2)} TB'

sign_file_id

Source code in django_spire/file/utils.py
def sign_file_id(file_id: int) -> str:
    return Signer().sign(str(file_id))

verify_file_token

Source code in django_spire/file/utils.py
def verify_file_token(file_id: int, token: str) -> bool:
    if not token:
        return False

    try:
        signed_id = Signer().unsign(token)
    except BadSignature:
        return False

    return str(file_id) == signed_id