Question

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.

Was it helpful?

Solution

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).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top