user764357
user764357

Reputation:

Finding when a django cache was set

I'm trying to implement intelligent cache invalidation in Django for my app with an algorithm of the sort:

page = get_cache_for_item(item_pk + some_key)
cache_set_at = page.SOMETHING_HERE
modified = models.Object.filter(pk=item_pk,modified__gt=cache_set_at).exists() #Cheap call
if modified:
    page = get_from_database_and_build_slowly(item_pk)
    set_cache_for_item(item_pk + some_key)
return page

The intent, is I want to do a quick call to the database to get the modified time, and if and only if the page was modified since the cache was set, build the page using the resource and database intensive page.

Unfortunately, I can't figure out how to get the time a cache was set at at the step SOMETHING_HERE.

Is this possible?

Upvotes: 0

Views: 592

Answers (1)

birkett
birkett

Reputation: 10101

Django does not seem to store that information. The information is (if stored) in the cache implementation of your choice.

This is for example, the way Django stores a key in memcached.

 def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
        key = self.make_key(key, version=version)
        if not self._cache.set(key, value, self.get_backend_timeout(timeout)):
            # make sure the key doesn't keep its old value in case of failure to set (memcached's 1MB limit)
            self._cache.delete(key)

Django does not store the creation time and lets the cache handle the timeout. So if any, you should look into the cache of your choice. I know that Redis, for example, does not store that value either, so you will not be able to make it work at all with redis, even if u bypass Django's cache and look into Redis.

I think your best choice is to store the key yourself somehow. You can maybe override the @cache_page or simply create an improved @smart_cache_page and store the timestamp of creation there.

EDIT:

There might be other easier ways to achieve that. You could use post_save signals. Something like this: Expire a view-cache in Django?

Read carefully through it since the implementation depends on your Django version.

Upvotes: 1

Related Questions