Skip to content

Commit

Permalink
Implement response_filter for memoized functions
Browse files Browse the repository at this point in the history
Fixes #107
  • Loading branch information
sh4nks committed Nov 24, 2019
1 parent 092e7cb commit 258bd0a
Showing 1 changed file with 21 additions and 12 deletions.
33 changes: 21 additions & 12 deletions flask_caching/__init__.py
Expand Up @@ -708,6 +708,7 @@ def memoize(
make_name=None,
unless=None,
forced_update=None,
response_filter=None,
hash_method=hashlib.md5,
cache_none=False,
):
Expand Down Expand Up @@ -765,6 +766,12 @@ def big_foo(a, b):
cache value will be updated regardless cache
is expired or not. Useful for background
renewal of cached functions.
:param response_filter: Default None. If not None, the callable is
invoked after the cached funtion evaluation,
and is given one arguement, the response
content. If the callable returns False, the
content will not be cached. Useful to prevent
caching of code 500 responses.
:param hash_method: Default hashlib.md5. The hash method used to
generate the keys for cached results.
:param cache_none: Default False. If set to True, add a key exists
Expand Down Expand Up @@ -825,18 +832,20 @@ def decorated_function(*args, **kwargs):

if not found:
rv = f(*args, **kwargs)
try:
self.cache.set(
cache_key,
rv,
timeout=decorated_function.cache_timeout,
)
except Exception:
if self.app.debug:
raise
logger.exception(
"Exception possibly due to cache backend."
)

if response_filter is None or response_filter(rv):
try:
self.cache.set(
cache_key,
rv,
timeout=decorated_function.cache_timeout,
)
except Exception:
if self.app.debug:
raise
logger.exception(
"Exception possibly due to cache backend."
)
return rv

decorated_function.uncached = f
Expand Down

0 comments on commit 258bd0a

Please sign in to comment.