django-dbtemplates/dbtemplates/utils/cache.py

69 lines
2 KiB
Python
Raw Normal View History

2021-06-22 13:40:53 +00:00
import django
2022-08-07 22:49:40 +00:00
from dbtemplates.conf import settings
2011-07-01 13:41:24 +00:00
from django.contrib.sites.models import Site
2022-08-07 22:49:40 +00:00
from django.core import signals
from django.template.defaultfilters import slugify
2011-07-01 13:41:24 +00:00
def get_cache_backend():
"""
Compatibilty wrapper for getting Django's cache backend instance
"""
2022-08-07 22:49:40 +00:00
if (django.VERSION[0] >= 3 and django.VERSION[1] >= 2) or django.VERSION[
0
] >= 4: # noqa
2021-06-22 13:40:53 +00:00
from django.core.cache import caches
2022-08-07 22:49:40 +00:00
2021-06-22 13:40:53 +00:00
cache = caches.create_connection(settings.DBTEMPLATES_CACHE_BACKEND)
else:
from django.core.cache import _create_cache
2022-08-07 22:49:40 +00:00
2021-06-22 13:40:53 +00:00
cache = _create_cache(settings.DBTEMPLATES_CACHE_BACKEND)
# Some caches -- python-memcached in particular -- need to do a cleanup at
# the end of a request cycle. If not implemented in a particular backend
# cache.close is a no-op
signals.request_finished.connect(cache.close)
return cache
2011-07-01 13:41:24 +00:00
2017-11-22 10:01:02 +00:00
2011-07-01 13:41:24 +00:00
cache = get_cache_backend()
def get_cache_key(name):
current_site = Site.objects.get_current()
2022-08-07 22:49:40 +00:00
return f"dbtemplates::{slugify(name)}::{current_site.pk}"
2011-07-01 13:41:24 +00:00
def get_cache_notfound_key(name):
2022-08-07 22:49:40 +00:00
return get_cache_key(name) + "::notfound"
def remove_notfound_key(instance):
# Remove notfound key as soon as we save the template.
cache.delete(get_cache_notfound_key(instance.name))
2011-07-01 13:41:24 +00:00
2011-07-01 13:50:04 +00:00
def set_and_return(cache_key, content, display_name):
2011-07-01 13:41:24 +00:00
# Save in cache backend explicitly if manually deleted or invalidated
if cache:
cache.set(cache_key, content)
return (content, display_name)
2011-07-01 13:50:04 +00:00
2011-07-01 13:41:24 +00:00
def add_template_to_cache(instance, **kwargs):
"""
Called via Django's signals to cache the templates, if the template
in the database was added or changed.
"""
remove_cached_template(instance)
remove_notfound_key(instance)
2011-07-01 13:41:24 +00:00
cache.set(get_cache_key(instance.name), instance.content)
def remove_cached_template(instance, **kwargs):
"""
Called via Django's signals to remove cached templates, if the template
in the database was changed or deleted.
"""
cache.delete(get_cache_key(instance.name))