From: Michael Tremer Date: Mon, 19 Nov 2018 16:57:29 +0000 (+0000) Subject: wiki: Cache thumbnail images in memcache X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=75d9b3dacf2966c8d6c6854ea8999c052e523fc8;p=ipfire.org.git wiki: Cache thumbnail images in memcache Signed-off-by: Michael Tremer --- diff --git a/src/backend/util.py b/src/backend/util.py index ff8248ea..89e7f0f5 100644 --- a/src/backend/util.py +++ b/src/backend/util.py @@ -3,6 +3,7 @@ import random import re import string +import unicodedata def parse_search_query(query): q = [] @@ -57,3 +58,15 @@ def random_string(length=8): r = (random.choice(input_chars) for i in range(length)) return "".join(r) + +def normalize(s): + # Remove any non-ASCII characters + try: + s = unicodedata.normalize("NFKD", s) + except TypeError: + pass + + # Remove excessive whitespace + s = re.sub(r"[^\w]+", " ", s) + + return "-".join(s.split()) diff --git a/src/backend/wiki.py b/src/backend/wiki.py index 0689fe49..33ed4040 100644 --- a/src/backend/wiki.py +++ b/src/backend/wiki.py @@ -348,6 +348,22 @@ class File(misc.Object): return bytes(res.data) def get_thumbnail(self, size): + cache_key = "-".join((self.path, util.normalize(self.filename), self.created_at.isoformat(), "%spx" % size)) + + # Try to fetch the data from the cache + thumbnail = self.memcache.get(cache_key) + if thumbnail: + return thumbnail + + # Generate the thumbnail + thumbnail = self._generate_thumbnail(size) + + # Put it into the cache for forever + self.memcache.set(cache_key, thumbnail) + + return thumbnail + + def _generate_thumbnail(self, size): image = PIL.Image.open(io.BytesIO(self.blob)) # Resize the image to the desired resolution