1

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?

1 Answers1

2

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.

Nour Wolf
  • 2,140
  • 25
  • 24
  • That's great! I was thinking that but your answer makes it really clear. There could be a way to catch that exception log? – Camilo Gómez May 07 '18 at 22:00
  • I believe you can do that by defining a custom handler and attaching it to `flask_cache` logger. There you could do what you want with the logs. – Nour Wolf May 09 '18 at 09:09