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?

KRTac
  • 2,767
  • 4
  • 22
  • 18

1 Answers1

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

Nickolay
  • 31,095
  • 13
  • 107
  • 185
Vaulstein
  • 20,055
  • 8
  • 52
  • 73
  • 2
    The link was broken, so I edited it to point to the Web Archive version. A [modern version of that page](https://flask.palletsprojects.com/en/1.1.x/patterns/caching/) instead points to the [Flask-Caching](https://flask-caching.readthedocs.io/en/latest/) extension. – Nickolay Oct 02 '19 at 11:15