Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 536
KRTac Avatar asked Oct 16 '15 07:10

KRTac


1 Answers

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

like image 111
Vaulstein Avatar answered Nov 07 '22 08:11

Vaulstein