Add cache and optimize code
This commit is contained in:
parent
2390968029
commit
473df39cbe
6 changed files with 114 additions and 54 deletions
|
@ -1,6 +1,7 @@
|
|||
from datetime import datetime
|
||||
from math import floor
|
||||
|
||||
from django.core.cache import cache
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import models
|
||||
from django.db.models import Sum
|
||||
|
@ -19,47 +20,30 @@ class Album(models.Model):
|
|||
cover = models.ForeignKey("Photo", blank=True, null=True, on_delete=models.SET_NULL, related_name='cover_to', verbose_name="Album cover")
|
||||
is_public = models.BooleanField(default=False, verbose_name="Published")
|
||||
|
||||
def _cache_key(self, suffix):
|
||||
return f'album_{self.pk}_{suffix}'
|
||||
|
||||
@property
|
||||
def photos_in_album(self):
|
||||
return self.photos.count()
|
||||
key = self._cache_key('photo_count')
|
||||
count = cache.get(key)
|
||||
|
||||
if count is None:
|
||||
count = self.photos.count()
|
||||
cache.set(key, count, 60 * 60 * 24) # Cache 24 h
|
||||
|
||||
return count
|
||||
|
||||
@property
|
||||
def photos_views(self):
|
||||
return self.photos.aggregate(total_views=Sum('views'))['total_views'] or 0
|
||||
key = self._cache_key('photo_views')
|
||||
views = cache.get(key)
|
||||
|
||||
if views is None:
|
||||
views = self.photos.aggregate(total_views=Sum('views'))['total_views'] or 0
|
||||
cache.set(key, views, 60 * 5) # Cache 5 min
|
||||
|
||||
@property
|
||||
def cover_image_data(self):
|
||||
def compute_size(photo, max_w=720, max_h=720):
|
||||
if not photo.width or not photo.height:
|
||||
return (None, None)
|
||||
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 (w, h)
|
||||
|
||||
photo = self.cover or self.photos.order_by('-width').first()
|
||||
if photo:
|
||||
url = photo.photo_md.url
|
||||
w, h = compute_size(photo)
|
||||
return {
|
||||
"url": url,
|
||||
"width": w,
|
||||
"height": h,
|
||||
"aspect_ratio": round(photo.aspect_ratio, 3)
|
||||
}
|
||||
|
||||
return {
|
||||
"url": static('img/placeholder.png'),
|
||||
"width": 1200,
|
||||
"height": 800,
|
||||
"aspect_ratio": 1.5
|
||||
}
|
||||
|
||||
return views
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
if not self.slug:
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue