Search code examples
pythoncachingflaskflask-cache

Storing simple key value pairs with Flask Cache and memcached


How can I store simple key value pairs with Flask Cache? Something like this:

cache.set('key', 'some value')
cache.get('key')

Now I only store a function's return value using the cache.cached() decorator. That method seams to work, but I don't know how to manually clear that function's cache before it timeouts on it's own.

Idealy, I would like to be able to set cache values based on a key, like in the example. Is that possible using memcached as the backend?


Solution

  • Flask has an in-built method for Caching where you can utilize Memcache to store Cache as key-value pairs:

    from werkzeug.contrib.cache import MemcachedCache
    cache = MemcachedCache(['127.0.0.1:11211'])
    
    def get_my_item():
        rv = cache.get('my-item')
        if rv is None:
            rv = calculate_value()
            cache.set('my-item', rv, timeout=5 * 60)
        return rv
    

    You can find more about it on Flask Cache