cache.get_or_set()

6 views
Skip to first unread message

Joseph Perla

unread,
Jan 31, 2007, 8:58:24 PM1/31/07
to django-d...@googlegroups.com
Along the lines of get_or_create(), does it make sense to implement a get_or_set() function for quick caches?

It can be used in this way:

    from django.core.cache import cache
    ...
    big_list = cache.get_or_set ('big_list', lambda: BigItems.objects.all(), 60 * 60)

to retrieve from cache or, if not in the cache, to cache the data for one hour in just one line of code.

Implement this in django.core.cache.backends.base as

    def get_or_set(self, key, value_function, timeout=None):
        _cached = cache.get(key)
        if not _cached:
            _cached = value_function()
            cache.set(key, _cached, timeout)
        return _cached

It looks a little funny with the lambda function, but I think it would be useful.  What do you think?
Thanks,
j

James Bennett

unread,
Jan 31, 2007, 9:19:31 PM1/31/07
to django-d...@googlegroups.com
On 1/31/07, Joseph Perla <josep...@gmail.com> wrote:
> Along the lines of get_or_create(), does it make sense to implement a
> get_or_set() function for quick caches?

I'm not sure I see the use case here; it only works when the code to
calculate the expensive value can be fit into a single statement, and
(in my experience at least) that's not usually how things work.

--
"Bureaucrat Conrad, you are technically correct -- the best kind of correct."

Jeremy Bowers

unread,
Jan 31, 2007, 10:13:29 PM1/31/07
to django-d...@googlegroups.com
James Bennett wrote:
> On 1/31/07, Joseph Perla <josep...@gmail.com> wrote:
>
>> Along the lines of get_or_create(), does it make sense to implement a
>> get_or_set() function for quick caches?
>>
>
> I'm not sure I see the use case here; it only works when the code to
> calculate the expensive value can be fit into a single statement, and
> (in my experience at least) that's not usually how things work.
>
I've been writing my own cache wrapper and I added something similar to
this. If the computations are expensive, it's helpful.

You of course wouldn't /have/ to use a lambda, you could pass in
whatever function you wanted. lambda is just for example purposes.

Gary Wilson

unread,
Feb 5, 2007, 3:46:16 PM2/5/07
to Django developers
On Jan 31, 7:58 pm, "Joseph Perla" <josephpe...@gmail.com> wrote:
> Along the lines of get_or_create(), does it make sense to implement a
> get_or_set() function for quick caches?

For the sake of discussion, there is a ticket with similar goals, but
only for QuerySets:
#5 - Add a cache=NUM_SECONDS argument to QuerySet
http://code.djangoproject.com/ticket/5

Reply all
Reply to author
Forward
0 new messages