Cache album cover data
This commit is contained in:
parent
473df39cbe
commit
f4a0edd091
1 changed files with 25 additions and 19 deletions
|
@ -1,29 +1,32 @@
|
|||
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),
|
||||
}
|
||||
|
||||
else:
|
||||
aspect = photo.aspect_ratio
|
||||
|
||||
if photo.width > photo.height:
|
||||
w = min(photo.width, max_w)
|
||||
h = floor(w / aspect)
|
||||
|
@ -31,9 +34,12 @@ def cover_image_data(album):
|
|||
h = min(photo.height, max_h)
|
||||
w = floor(h * aspect)
|
||||
|
||||
return {
|
||||
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
|
Loading…
Add table
Reference in a new issue