Search code examples
pythongoogle-app-enginewebwebapp2

"Optimizing Queries" video (Udacity web dev course), caching db queries


Here is the video that I am confused about: https://www.youtube.com/watch?v=9UHKsiDznwg

At about 6:12 you can see the code he uses to cache database queries. What I don't understand is why he uses a dictionary to cache the queries. The way he has it set up won't the dictionary only ever store one value at the 'top' key that he sets. Why doesn't he just store it in a variable? I have included the main code in question as well.

CACHE = {}
def top_arts():
    key = 'top'
    if key in CACHE:
        arts = CACHE[key]
    else:
        logging.error("DB QUERY")
        arts = db.GqlQuery("SELECT * "
                           "FROM Art"
                           "WHERE ANCESTOR IS :1"
                           "ORDER BY created DESC"
                           "LIMIT 10",
                           art_key)
        arts = list(arts)
        CACHE[key] = arts
    return arts

Solution

  • The example has a single value, true, but it's just an example, often there are multiple cache-able values in an app. The pattern supports any number of cached values.

    It's just a matter of habit - keeping the entire cache together, one can operate on it easily - like seeing what's in the cache, etc. It'd be rather difficult to do that with a pile of independent variables scattered all over the code.

    Of course, it's a subjective matter. Some may object to it, for example as being risky: if accidentally using the same key in different places cache values would get corrupted - quite likely not a trivial bug to chase.