From f4a0edd091bd637459b09fa8975941656f80029c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9DNyymix=E2=80=9D?= Date: Mon, 14 Apr 2025 10:36:06 +0300 Subject: [PATCH] Cache album cover data --- gallery/templatetags/image_tags.py | 44 +++++++++++++++++------------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/gallery/templatetags/image_tags.py b/gallery/templatetags/image_tags.py index d129897..387d8ba 100644 --- a/gallery/templatetags/image_tags.py +++ b/gallery/templatetags/image_tags.py @@ -1,39 +1,45 @@ from math import floor from django import template +from django.core.cache import cache from django.templatetags.static import static register = template.Library() @register.filter def cover_image_data(album): - """ - Palauttaa dictin: url, width, height, aspect_ratio. - Jos coveria ei ole, palauttaa placeholder-kuvan ja oletusmitat. - """ + + cache_key = f'cover_image_data_{album.pk}' + data = cache.get(cache_key) + + if data: + return data + photo = getattr(album, "cover", None) max_w, max_h = 720, 720 if not photo or not photo.width or not photo.height: - return { + data = { "url": static("img/placeholder.png"), "width": 1200, "height": 800, "aspect_ratio": round(1200 / 800, 3), } - - aspect = photo.aspect_ratio - - if photo.width > photo.height: - w = min(photo.width, max_w) - h = floor(w / aspect) else: - h = min(photo.height, max_h) - w = floor(h * aspect) + aspect = photo.aspect_ratio + if photo.width > photo.height: + w = min(photo.width, max_w) + h = floor(w / aspect) + else: + h = min(photo.height, max_h) + w = floor(h * aspect) - return { - "url": photo.photo_md.url, - "width": w, - "height": h, - "aspect_ratio": round(aspect, 3), - } + data = { + "url": photo.photo_md.url, + "width": w, + "height": h, + "aspect_ratio": round(aspect, 3), + } + + cache.set(cache_key, data, 60 * 60 * 24) + return data \ No newline at end of file