diff --git a/bookwyrm/templatetags/interaction.py b/bookwyrm/templatetags/interaction.py index 7aaaaca7e..c9f08fb31 100644 --- a/bookwyrm/templatetags/interaction.py +++ b/bookwyrm/templatetags/interaction.py @@ -1,8 +1,8 @@ """ template filters for status interaction buttons """ from django import template -from django.core.cache import cache from bookwyrm import models +from bookwyrm.utils.cache import get_or_set register = template.Library() @@ -11,20 +11,23 @@ register = template.Library() @register.filter(name="liked") def get_user_liked(user, status): """did the given user fav a status?""" - return cache.get_or_set( + return get_or_set( f"fav-{user.id}-{status.id}", - models.Favorite.objects.filter(user=user, status=status).exists(), - 259200, + lambda u, s: models.Favorite.objects.filter(user=u, status=s).exists(), + user, + status, + timeout=259200 ) @register.filter(name="boosted") def get_user_boosted(user, status): """did the given user fav a status?""" - return cache.get_or_set( + return get_or_set( f"boost-{user.id}-{status.id}", - status.boosters.filter(user=user).exists(), - 259200, + lambda u: status.boosters.filter(user=u).exists(), + user, + timeout=259200, ) @@ -33,15 +36,20 @@ def get_user_saved_lists(user, book_list): """did the user save a list""" return user.saved_lists.filter(id=book_list.id).exists() + @register.simple_tag(takes_context=True) def get_relationship(context, user_object): """caches the relationship between the logged in user and another user""" user = context["request"].user - return cache.get(f"relationship-{user.id}-{user_object.id}") or cache.set( - get_relationship_name(user, user_object), + return get_or_set( + f"relationship-{user.id}-{user_object.id}", + get_relationship_name, + user, + user_object, timeout=259200, ) + def get_relationship_name(user, user_object): """returns the relationship type""" types = { diff --git a/bookwyrm/utils/cache.py b/bookwyrm/utils/cache.py new file mode 100644 index 000000000..2fca1264a --- /dev/null +++ b/bookwyrm/utils/cache.py @@ -0,0 +1,10 @@ +""" Custom handler for caching """ +from django.core.cache import cache + + +def get_or_set(cache_key, function, *args, timeout=None): + """Django's built-in get_or_set isn't cutting it""" + value = cache.get(cache_key) + if value is None: + cache.set(cache_key, function(*args), timeout=timeout) + return cache.get(cache_key)