Creates custom get_or_set function

This commit is contained in:
Mouse Reeve 2022-01-08 12:59:56 -08:00
parent 2cca9fab2d
commit f2f40cf3b9
2 changed files with 27 additions and 9 deletions

View file

@ -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 = {

10
bookwyrm/utils/cache.py Normal file
View file

@ -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)