get_stamp for CacheClass?

11 views
Skip to first unread message

Jerry Stratton

unread,
Sep 1, 2009, 2:13:12 PM9/1/09
to Django developers
As I'm working with caches, I've found myself wanting to know when the
cache was created, to compare against the last time some data was
updated.

I looked at filebased.py in core/cache/backends and added:

def get_stamp(self, key, timeout=None):
fname = self._key_to_file(key)
try:
f = open(fname, 'rb')
exp = pickle.load(f)
f.close()
if timeout:
exp = exp - timeout
return exp
except(IOError, OSError, EOFError, pickle.PickleError):
pass
return 0

I based it off of the "get" method.

Is this worth submitting as a feature ticket? (Obviously a not-
implemented version would have to be added to the base class, too.)

I use it like this:

def personalProjects(self):
#cache for a long time (one day)--if there's new stuff, we'll
recache anyway
cacheTime = 60*60*24
cacheKey = 'personal-projects-' + str(self.id)

rawTasks = Task.objects.filter(assignees=self)

#if anything has changed since the last cache, need to recreate
the cache
cacheDate = datetime.datetime.fromtimestamp(cache.get_stamp
(cacheKey, cacheTime))
recentTasks = rawTasks.filter(edited__gte=cacheDate)

if not recentTasks:
openProjects = cache.get(cacheKey)
if openProjects:
return openProjects

#do time-intensive calculations to find and organize projects from
tasks
...

cache.set(cacheKey, openProjects, cacheTime)
return openProjects

Jerry

Thomas K. Adamcik

unread,
Sep 2, 2009, 5:09:49 AM9/2/09
to django-d...@googlegroups.com
On Tue, Sep 01, 2009 at 11:13:12AM -0700, Jerry Stratton wrote:
> As I'm working with caches, I've found myself wanting to know when the
> cache was created, to compare against the last time some data was
> updated.

Simply using cache.set('your_cache_key', (datetime.now(), your_value)) (or
time() instead of datetime.now()) should allow you to keep track of this in a
way which doesn't require modifying any core Django functionality :)

You might want to combine this with a custom version of the cache-middleware
and/or -decorator ;)

--
Thomas Adamcik

Jerry Stratton

unread,
Sep 5, 2009, 5:34:07 PM9/5/09
to Django developers
On Sep 2, 2:09 am, "Thomas K. Adamcik" <tadam...@gmail.com> wrote:
> Simply using cache.set('your_cache_key', (datetime.now(), your_value)) (or
> time() instead of datetime.now()) should allow you to keep track of this in a
> way which doesn't require modifying any core Django functionality :)

Thanks; that makes sense.
Reply all
Reply to author
Forward
0 new messages