Search code examples
pythonflaskredisflask-caching

flask caching - handle exception when redis service is down


I have a simple code using flask:

@app.route('/foo/<arg>')
@app.cache.memoize()
def foo_response(arg):
    return 'Hello ' + arg

This is working great while my redis server (cache server) is up.

If the redis server goes down, an exception is raised every time I query /foo/<arg>, which is understandable.

How (and where) can I handle that exception (à la try-except) in order to not use the redis server if it is down at that moment?


Solution

  • It is actually implemented this way. By checking the source of memoize() in Flask-Cache package you see

            try:
                cache_key = decorated_function.make_cache_key(f, *args, **kwargs)
                rv = self.cache.get(cache_key)
            except Exception:
                if current_app.debug:
                    raise
                logger.exception("Exception possibly due to cache backend.")
                return f(*args, **kwargs)
    

    This means if you are on production i.e. app.debug=False you will see the exception log and the function will be called normally.