Storing simple key value pairs with Flask Cache and memcached
Asked Answered
T

1

6

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?

Towle answered 16/10, 2015 at 7:59 Comment(0)
P
11

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

Ptolemaist answered 16/10, 2015 at 8:14 Comment(1)
The link was broken, so I edited it to point to the Web Archive version. A modern version of that page instead points to the Flask-Caching extension.Mortar

© 2022 - 2024 — McMap. All rights reserved.