[Django]-Caching results of a Django function call with cache.get_or_set()

10👍

No, not at all. Python must evaluate expressions that form part of the arguments to a function fully before calling the function itself. In your second case this means that self.get_google_events() will always be called, before get_or_set can determine whether or not not retrieve the value from the cache.

Note also that your first case can be made slightly more efficient: the way you have it now, you’re making two calls to get unnecessarily. Instead, just make one:

events = cache.get(cache_name)
if not events:
    events = self.get_google_events()
    cache.set(cache_name, events, 60 * 10)

5👍

The solution is not to call the function (without () ).
In your case it is:

events = cache.get_or_set(cache_name, self.get_google_events, 60 * 10)

You can test it with this example from the django documentation

import datetime
from django.core.cache import cache

cache.get_or_set('some-timestamp-key', datetime.datetime.now)

>> datetime.datetime(2014, 12, 11, 0, 15, 49, 457920)

you normally call it with datetime.datetime.now()

see documentation Django’s cache framework

Leave a comment