From 9928f4cda062f0d55b070a3e547137802850823c Mon Sep 17 00:00:00 2001 From: long2ice Date: Thu, 28 Oct 2021 15:52:21 +0800 Subject: [PATCH] Add `enable` param to `init` --- CHANGELOG.md | 1 + fastapi_cache/__init__.py | 7 +++++++ fastapi_cache/decorator.py | 4 +++- 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a4207d5..d0cccc4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### 0.1.7 - Fix default json coder for datetime. +- Add `enable` param to `init`. ### 0.1.6 diff --git a/fastapi_cache/__init__.py b/fastapi_cache/__init__.py index 079aeb4..4f92bb8 100644 --- a/fastapi_cache/__init__.py +++ b/fastapi_cache/__init__.py @@ -11,6 +11,7 @@ class FastAPICache: _init = False _coder = None _key_builder = None + _enable = True @classmethod def init( @@ -20,6 +21,7 @@ class FastAPICache: expire: int = None, coder: Coder = JsonCoder, key_builder: Callable = default_key_builder, + enable: bool = True, ): if cls._init: return @@ -29,6 +31,7 @@ class FastAPICache: cls._expire = expire cls._coder = coder cls._key_builder = key_builder + cls._enable = enable @classmethod def get_backend(cls): @@ -51,6 +54,10 @@ class FastAPICache: def get_key_builder(cls): return cls._key_builder + @classmethod + def get_enable(cls): + return cls._enable + @classmethod async def clear(cls, namespace: str = None, key: str = None): namespace = cls._prefix + ":" + namespace if namespace else None diff --git a/fastapi_cache/decorator.py b/fastapi_cache/decorator.py index 07573b1..7b60408 100644 --- a/fastapi_cache/decorator.py +++ b/fastapi_cache/decorator.py @@ -29,7 +29,9 @@ def cache( copy_kwargs = kwargs.copy() request = copy_kwargs.pop("request", None) response = copy_kwargs.pop("response", None) - if request and request.headers.get("Cache-Control") == "no-store": + if ( + request and request.headers.get("Cache-Control") == "no-store" + ) or not FastAPICache.get_enable(): return await func(*args, **kwargs) coder = coder or FastAPICache.get_coder()