diff --git a/CHANGELOG.md b/CHANGELOG.md index c7ab938..49a047f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ - Add `py.typed` file and type hints - Add TestCase - Fix cache decorate sync function +- Transparently handle backend connection failures. ### 0.2.0 diff --git a/fastapi_cache/decorator.py b/fastapi_cache/decorator.py index 2585a45..bcfe9b5 100644 --- a/fastapi_cache/decorator.py +++ b/fastapi_cache/decorator.py @@ -123,13 +123,18 @@ def cache( args=args, kwargs=copy_kwargs, ) - - ttl, ret = await backend.get_with_ttl(cache_key) + try: + ttl, ret = await backend.get_with_ttl(cache_key) + except ConnectionError: + ttl, ret = 0, None if not request: if ret is not None: return coder.decode(ret) ret = await ensure_async_func(*args, **kwargs) - await backend.set(cache_key, coder.encode(ret), expire or FastAPICache.get_expire()) + try: + await backend.set(cache_key, coder.encode(ret), expire or FastAPICache.get_expire()) + except ConnectionError: + pass return ret if request.method != "GET": @@ -148,7 +153,10 @@ def cache( ret = await ensure_async_func(*args, **kwargs) - await backend.set(cache_key, coder.encode(ret), expire or FastAPICache.get_expire()) + try: + await backend.set(cache_key, coder.encode(ret), expire or FastAPICache.get_expire()) + except ConnectionError: + pass return ret return inner