Skip to content

meringue.thumbnail.drf_fields ¤

BaseImageField ¤

BaseImageField(
    size=None, job_chain=None, locked_dummy=True, **kwargs
)

Bases: ImageField

Attributes:

  • size –

    Thumbnail size.

  • job_chain –

    Thumbnail job chain (instead of size).

  • locked_dummy –

    Return the dummy image instead of the thumbnail URL while the thumbnail is being made by another process (the file may not exist yet, and the browser could cache a broken URL).

  • **kwargs –

    ImageField params.

Source code in meringue/thumbnail/drf_fields.py
def __init__(self, size=None, job_chain=None, locked_dummy=True, **kwargs):
    """
    Attributes:
        size: Thumbnail size.
        job_chain: Thumbnail job chain (instead of `size`).
        locked_dummy: Return the dummy image instead of the thumbnail URL while the thumbnail
            is being made by another process (the file may not exist yet, and the browser
            could cache a broken URL).
        **kwargs: `ImageField` params.
    """

    self.locked_dummy = locked_dummy

    if bool(size) and bool(job_chain):
        msg = "Need to set `size` or `job_chain` attribute (not both)."
        raise ValueError(msg)

    elif size:
        self.job_chain = [
            f"s:{size[0]}x{size[1]}",
            "rm:cover",
            "rs:no_increase",
            "resize",
        ]

    elif job_chain:
        self.job_chain = job_chain

    else:
        self.job_chain = []

    super().__init__(**kwargs)

MImageField ¤

MImageField(
    size=None, job_chain=None, locked_dummy=True, **kwargs
)

Bases: BaseImageField

Optimize image to represent them

Source code in meringue/thumbnail/drf_fields.py
def __init__(self, size=None, job_chain=None, locked_dummy=True, **kwargs):
    """
    Attributes:
        size: Thumbnail size.
        job_chain: Thumbnail job chain (instead of `size`).
        locked_dummy: Return the dummy image instead of the thumbnail URL while the thumbnail
            is being made by another process (the file may not exist yet, and the browser
            could cache a broken URL).
        **kwargs: `ImageField` params.
    """

    self.locked_dummy = locked_dummy

    if bool(size) and bool(job_chain):
        msg = "Need to set `size` or `job_chain` attribute (not both)."
        raise ValueError(msg)

    elif size:
        self.job_chain = [
            f"s:{size[0]}x{size[1]}",
            "rm:cover",
            "rs:no_increase",
            "resize",
        ]

    elif job_chain:
        self.job_chain = job_chain

    else:
        self.job_chain = []

    super().__init__(**kwargs)

get_thumbnail ¤

get_thumbnail(path: Path | Any) -> ThumbnailImage

Generates (if needed) and returns the thumbnail in the source image format.

Attributes:

  • path –

    Source image: a model FieldFile (any storage, including S3) or an absolute local path.

Returns:

Source code in meringue/thumbnail/drf_fields.py
def get_thumbnail(self, path: Path | Any) -> ThumbnailImage:
    """
    Generates (if needed) and returns the thumbnail in the source image format.

    Attributes:
        path: Source image: a model `FieldFile` (any storage, including S3) or an
            absolute local path.

    Returns:
        Thumbnail image.
    """

    source = ThumbnailSource.from_value(path)
    thumbnail = DefaultThumbnailer(source, job_chain=self.job_chain)
    return thumbnail.get_thumbnail(source.format)

to_representation ¤

to_representation(value)

The source file is not read (and its existence is not checked) if the thumbnail is already saved. If the thumbnail can't be made (any error), the error is logged and the dummy image is returned.

TODO
  • Add params to get_thumbnail for optimize images
Source code in meringue/thumbnail/drf_fields.py
def to_representation(self, value):
    """
    The source file is not read (and its existence is not checked) if the thumbnail is
    already saved. If the thumbnail can't be made (any error), the error is logged and the
    dummy image is returned.

    TODO:
        * Add params to get_thumbnail for optimize images
    """

    if not value:
        return None

    try:
        thumbnail = self.get_thumbnail(value)
        url = thumbnail.url

    except FileNotFoundError:
        logger.error("File `%s` not found", value.name)
        result = get_dummy_image_url()

    except Exception:
        # one broken image must not break the whole serializer response
        logger.exception("Failed to make a thumbnail for image `%s`", value.name)
        result = get_dummy_image_url()

    else:
        locked = thumbnail.locked and self.locked_dummy
        result = get_dummy_image_url() if locked else url

    return result

MImageSetField ¤

MImageSetField(
    size=None,
    dimensions=(1, 2),
    base_job_chain=None,
    job_chains=None,
    locked_dummy=True,
    **kwargs
)

Bases: ImageField

Image field - make multiple files in different formats.

Can set size (eg '100x100'), job_chain (arrays of jobs by dimensions) or nothing to optimize images only

Attributes:

  • size –

    Thumbnail size for the 1x dimension.

  • dimensions –

    Dimensions (pixel densities).

  • base_job_chain –

    Job chain after the size (rm:cover, resize, crop by default).

  • job_chains –

    Job chains by dimensions (instead of size).

  • locked_dummy –

    Return the dummy image instead of the thumbnail set while any thumbnail is being made by another process (the file may not exist yet, and the browser could cache a broken URL).

  • **kwargs –

    ImageField params.

Source code in meringue/thumbnail/drf_fields.py
def __init__(
    self,
    size=None,
    dimensions=(1, 2),
    base_job_chain=None,
    job_chains=None,
    locked_dummy=True,
    **kwargs,
):
    """
    Attributes:
        size: Thumbnail size for the 1x dimension.
        dimensions: Dimensions (pixel densities).
        base_job_chain: Job chain after the size (`rm:cover, resize, crop` by default).
        job_chains: Job chains by dimensions (instead of `size`).
        locked_dummy: Return the dummy image instead of the thumbnail set while any thumbnail
            is being made by another process (the file may not exist yet, and the browser
            could cache a broken URL).
        **kwargs: `ImageField` params.
    """

    self.locked_dummy = locked_dummy

    if size and job_chains:
        msg = "Need to set 'size' or 'job_chains' attribute (not both)."
        raise ValueError(msg)

    elif size:
        if not dimensions:
            msg = (
                "If you specify the 'sizes' attribute, "
                "then the 'dimensions' attribute cannot be empty."
            )
            raise ValueError(msg)

        self.job_chains = {}

        dimensions = list(dimensions)
        if 1 not in dimensions:
            dimensions.insert(0, 1)

        for dimension in dimensions:
            self.job_chains[dimension] = [
                f"s:{round(size[0]*dimension)}x{round(size[1]*dimension)}",
                *(base_job_chain or ["rm:cover", "resize", "crop"]),
            ]

    elif job_chains:
        self.job_chains = job_chains

    else:
        self.job_chains = {}

    self.spectacular_annotate()
    super().__init__(**kwargs)

iter_thumbnails ¤

iter_thumbnails(
    path: Path | Any,
) -> Iterator[tuple[int, ThumbnailImage, ThumbnailImage]]

Generates (if needed) thumbnails for each dimension.

The source is read and decoded once for all dimensions, and each dimension is resized once for both formats.

Attributes:

  • path –

    Source image: a model FieldFile (any storage, including S3) or an absolute local path.

Yields:

Source code in meringue/thumbnail/drf_fields.py
def iter_thumbnails(
    self,
    path: Path | Any,
) -> Iterator[tuple[int, ThumbnailImage, ThumbnailImage]]:
    """
    Generates (if needed) thumbnails for each dimension.

    The source is read and decoded once for all dimensions, and each dimension is resized once
    for both formats.

    Attributes:
        path: Source image: a model `FieldFile` (any storage, including S3) or an
            absolute local path.

    Yields:
        Dimension, thumbnail in the source image format and WebP thumbnail.
    """

    source = ThumbnailSource.from_value(path)
    original_format = source.format

    for dimension, job_chain in self.job_chains.items():
        thumbnail = DefaultThumbnailer(source, job_chain=job_chain)
        original = thumbnail.get_thumbnail(original_format)
        webp_thumbnail = thumbnail.get_thumbnail("WEBP")
        yield dimension, original, webp_thumbnail

to_representation ¤

to_representation(value)

Creates multiple images. Image with format as original image and webp.

The source file is not read (and its existence is not checked) if all thumbnails are already saved. If any thumbnail can't be made (any error), the error is logged and the dummy image is returned instead of the whole set.

TODO
  • Add params to get_thumbnail for optimize images
  • In future make av1 image
  • Check enabled webp
Source code in meringue/thumbnail/drf_fields.py
def to_representation(self, value):
    """
    Creates multiple images. Image with format as original image and webp.

    The source file is not read (and its existence is not checked) if all thumbnails are
    already saved. If any thumbnail can't be made (any error), the error is logged and the
    dummy image is returned instead of the whole set.

    TODO:
        * Add params to get_thumbnail for optimize images
        * In future make av1 image
        * Check enabled webp
    """

    if not value:
        return None

    result = []

    try:
        for dimension, original, webp_thumbnail in self.iter_thumbnails(value):
            if self.locked_dummy and (original.locked or webp_thumbnail.locked):
                return self.get_dummy_representation()

            if dimension == 1:
                result = [
                    {"srcset": f"{webp_thumbnail.url} 1x", "type": webp_thumbnail.mimetype},
                    {"srcset": f"{original.url} 1x", "type": original.mimetype},
                ]

            else:
                result[0][
                    "srcset"
                ] = f"{result[0]['srcset']}, {webp_thumbnail.url} {dimension}x"
                result[1]["srcset"] = f"{result[1]['srcset']}, {original.url} {dimension}x"

    except FileNotFoundError:
        logger.error("File `%s` not found", value.name)
        return self.get_dummy_representation()

    except Exception:
        # one broken image must not break the whole serializer response
        logger.exception("Failed to make a thumbnail for image `%s`", value.name)
        return self.get_dummy_representation()

    return result