Skip to content

meringue.thumbnail.sources ¤

Thumbnail source images.

The source image can be a local file (Path) or a file in any Django storage (a model FieldFile or a name plus a storage). ThumbnailSource reads and decodes it at most once, so all sizes and formats made from one source share a single download and a single decode.

SOURCE_ATTR module-attribute ¤

SOURCE_ATTR: Final[str] = '_meringue_thumbnail_source'

The attribute of a FieldFile where its ThumbnailSource is kept.

One FieldFile is shared by all fields of a model instance during serialization, so all sizes and formats of one image reuse a single download and a single decode.

get_client_error_code ¤

get_client_error_code(error: BaseException) -> str | None

Returns the error code of a botocore ClientError without importing botocore.

Attributes:

  • error –

    Any exception.

Returns:

  • str | None –

    Error code or None.

Source code in meringue/thumbnail/sources.py
def get_client_error_code(error: BaseException) -> str | None:
    """
    Returns the error code of a botocore `ClientError` without importing botocore.

    Attributes:
        error: Any exception.

    Returns:
        Error code or `None`.
    """

    response = getattr(error, "response", None)

    if not isinstance(response, dict):
        return None

    return response.get("Error", {}).get("Code")

read_s3_file ¤

read_s3_file(storage: Storage, name: str) -> bytes

Reads an S3 object with a single GET request.

S3Storage.open() sends a HEAD request (obj.load()) before the GET.

Attributes:

  • storage –

    django-storages S3 storage.

  • name –

    File name in the storage.

Raises:

Returns:

  • bytes –

    File content.

Source code in meringue/thumbnail/sources.py
def read_s3_file(storage: Storage, name: str) -> bytes:
    """
    Reads an S3 object with a single GET request.

    `S3Storage.open()` sends a HEAD request (`obj.load()`) before the GET.

    Attributes:
        storage: django-storages S3 storage.
        name: File name in the storage.

    Raises:
        FileNotFoundError: There is no such object.

    Returns:
        File content.
    """

    clean_name = getattr(storage, "_clean_name", None)

    if clean_name is None:
        from storages.utils import clean_name  # noqa: PLC0415

    key = storage._normalize_name(clean_name(name))

    try:
        return storage.bucket.Object(key).get()["Body"].read()
    except Exception as error:
        if get_client_error_code(error) in S3_MISSING_KEY_CODES:
            raise FileNotFoundError(name) from error
        raise

ThumbnailSource ¤

ThumbnailSource(
    name: str | Path, storage: Storage | None = None
)

Source image of thumbnails.

Attributes:

  • name –

    Absolute path to a local file (without storage) or file name in the storage.

  • storage –

    Source file storage.

Raises:

Source code in meringue/thumbnail/sources.py
def __init__(self, name: str | Path, storage: Storage | None = None):
    """
    Attributes:
        name: Absolute path to a local file (without storage) or file name in the storage.
        storage: Source file storage.

    Raises:
        AttributeError: Local path is not absolute.
    """

    if storage is None:
        name = Path(name)

        if not name.is_absolute():
            msg = "`image_path` must be absolute"
            raise AttributeError(msg, name="image_path")

    self.name = name
    self.storage = storage
    self._image = None

from_value classmethod ¤

from_value(value: Any) -> ThumbnailSource

Makes a source from a Path, a FieldFile (or any object with name and storage attributes) or returns an existing source as is.

The source of a FieldFile is cached on it.

Attributes:

  • value –

    Source image.

Returns:

Source code in meringue/thumbnail/sources.py
@classmethod
def from_value(cls, value: Any) -> "ThumbnailSource":
    """
    Makes a source from a `Path`, a `FieldFile` (or any object with `name` and `storage`
    attributes) or returns an existing source as is.

    The source of a `FieldFile` is cached on it.

    Attributes:
        value: Source image.

    Returns:
        Thumbnail source.
    """

    if isinstance(value, ThumbnailSource):
        return value

    if isinstance(value, (str, Path)):
        return cls(Path(value))

    source = getattr(value, SOURCE_ATTR, None)

    if source is None or source.name != value.name or source.storage is not value.storage:
        source = cls(value.name, value.storage)

        with contextlib.suppress(AttributeError):
            setattr(value, SOURCE_ATTR, source)

    return source

path cached property ¤

path: Path | None

Absolute path to the source file or None if the storage has no local paths.

key property ¤

key: str

The source identifier used for the thumbnail hash.

The absolute path for local files (so the thumbnails of the Path and of the FieldFile of the same file are the same) and the file name for remote storages.

format property ¤

format: str

Image format of the source file, detected by its extension.

Raises:

read ¤

read() -> bytes

Reads the source file with as few storage requests as possible.

Raises:

Returns:

  • bytes –

    File content.

Source code in meringue/thumbnail/sources.py
def read(self) -> bytes:
    """
    Reads the source file with as few storage requests as possible.

    Raises:
        FileNotFoundError: The source file does not exist.

    Returns:
        File content.
    """

    if self.is_local:
        return self.name.read_bytes()

    if is_s3_storage_class(type(self.storage)):
        return read_s3_file(self.storage, self.name)

    with self.storage.open(self.name, "rb") as source_file:
        return source_file.read()

image property ¤

image: Image

Decoded RGBA source image. It is read and decoded only once.

Thumbnail actions return new images and never change the source in place, so it is safe to share it.