1

I am using per-view cache in Django and I want to refresh the cache whenever it get's stale. In the documentation I see no information on refreshing stale cache and after going through several threads I decided to use django-signals to send a signal to a function which will delete the cache records from DB. So my problem is how do we retrieve the keys and delete it?

I see the default implementation provides a way to give an expiration time to cache (as in @cache_page(60 * 15) and it refreshes whenever we call the view after expiration time. Is there any way to refresh stale cache not based on predefined time?

PVSK
  • 126
  • 1
  • 8

2 Answers2

2

I found some solutions here (Expire a view-cache in Django?). It's mostly related to memcached data, but mine is database cached data.

I came up with Django signals to call a function to clear all the cache related to my view. As retrieving keys is not a straightforward thing in db cached data, I simply passed raw SQL to delete the view cache. below is the code snippet.

Note: As I only have one cached view, I am simply deleting it, but if you have multiple per view caches in the cache table you need to be careful when deleting the cache data

cache_table is the name defined to your cache table in settings.py

CACHES = {
'default': {
    'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
    'LOCATION': 'cache_table',
}}



@receiver(post_save, sender=SampleModel)
def remove_cache(instance, **kwargs):
with connection.cursor() as cursor:
    cursor.execute("DELETE FROM cache_table where cache_key like ('%views.decorators.cache%')")
    print('Deleted view cache')
PVSK
  • 126
  • 1
  • 8
0

Another approach is creating your own cache and creating your own keys using the django low-level cache API. This is easy and gives you more control over the cached data.

PVSK
  • 126
  • 1
  • 8