How to disable Flask-Cache caching

a.m. picture a.m. · Jan 3, 2014 · Viewed 25.6k times · Source

I meet a problem while using Flask-Cache. I need to make caching on need basis, by defining a configuration variable which user can set for enable or disable caching.

I'm using Flask-Cache for caching purposes, as

cache = Cache(config={'CACHE_TYPE': 'redis'})
app = Flask(__name__)

# To initialize cache 
cache.init_app(app)

# clear cache
with app.app_context():
    cache.clear()

And using cache(in views.py) as

@app.route('/<int:id>', methods=['GET'])

@validate_access(current_user, "read")

@login_required

@cache.memoize()

def get_values(id):
    return get_values()

I'm not getting the correct way to make enable/ disable caching while using Flask-Cache. Is there a standard way by which we can enable/disable the cache behavior entirely.

Answer

Sean Vieira picture Sean Vieira · Jan 3, 2014

Simply set your app.config's CACHE_TYPE key to "null" before you initialize Flask-Cache:

app.config["CACHE_TYPE"] = "null"
# change to "redis" and restart to cache again

# some time later
cache.init_app(app)

# All caching functions will simply call through
# to the wrapped function, with no caching
# (since NullCache does not cache).