Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Send Flask signals for cache hits and misses #237

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ The following configuration values exist for Flask-Caching:
RedisSentinelCache.
``CACHE_REDIS_SENTINEL_MASTER`` The name of the master server in a sentinel configuration. Used
only for RedisSentinelCache.
``CACHE_REDIS_CLUSTER`` A string of comma-separated Redis cluster node addresses.
``CACHE_REDIS_CLUSTER`` A string of comma-separated Redis cluster node addresses.
e.g. host1:port1,host2:port2,host3:port3 . Used only for RedisClusterCache.
``CACHE_DIR`` Directory to store cache. Used only for
FileSystemCache.
Expand All @@ -404,6 +404,7 @@ The following configuration values exist for Flask-Caching:
protocols ``redis://``, ``rediss://`` (redis over TLS) and
``unix://``. See more info about URL support [here](http://redis-py.readthedocs.io/en/latest/index.html#redis.ConnectionPool.from_url).
Used only for RedisCache.
``CACHE_ENABLE_SIGNALS`` Send Flask Signals for :meth:`~Cache.cached` and :meth:`~Cache.memoize` cache hits and misses.
=============================== ==================================================================


Expand Down Expand Up @@ -677,6 +678,20 @@ username/password if SASL is enabled on the library::
With this example, your ``CACHE_TYPE`` might be ``the_app.custom.pylibmccache``


Signals
-------

The following signals are supported::

* ``flask_caching.cache_view_hit``
* ``flask_caching.cache_view_miss``
* ``flask_caching.cache_memoize_hit``
* ``flask_caching.cache_memoize_miss``

By default, signals are disabled. To enable sending signals set
``CACHE_ENABLE_SIGNALS`` to ``True``.


API
---

Expand Down
25 changes: 25 additions & 0 deletions flask_caching/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from collections import OrderedDict

from flask import current_app, request, url_for, Flask
from flask.signals import Namespace
from werkzeug.utils import import_string
from flask_caching.backends.base import BaseCache
from flask_caching.backends.simplecache import SimpleCache
Expand All @@ -29,6 +30,8 @@

logger = logging.getLogger(__name__)

_signals = Namespace()

TEMPLATE_FRAGMENT_KEY_TEMPLATE = "_template_fragment_cache_%s%s"
SUPPORTED_HASH_FUNCTIONS = [
hashlib.sha1,
Expand All @@ -44,6 +47,11 @@
delchars = "".join(c for c in map(chr, range(256)) if c not in valid_chars)
null_control = (dict((k, None) for k in delchars),)

cache_view_hit = _signals.signal('cache-view-hit')
cache_view_miss = _signals.signal('cache-view-miss')
cache_memoize_hit = _signals.signal('cache-memoize-hit')
cache_memoize_miss = _signals.signal('cache-memoize-miss')


def wants_args(f: Callable) -> bool:
"""Check if the function wants any arguments"""
Expand Down Expand Up @@ -193,6 +201,7 @@ def init_app(self, app: Flask, config=None) -> None:
config.setdefault("CACHE_TYPE", "null")
config.setdefault("CACHE_NO_NULL_WARNING", False)
config.setdefault("CACHE_SOURCE_CHECK", False)
config.setdefault("CACHE_ENABLE_SIGNALS", False)

if (
config["CACHE_TYPE"] == "null"
Expand Down Expand Up @@ -471,6 +480,14 @@ def decorated_function(*args, **kwargs):
logger.exception("Exception possibly due to cache backend.")
return f(*args, **kwargs)

if self.config["CACHE_ENABLE_SIGNALS"]:
if found:
cache_view_hit.send(cache=self, cache_key=cache_key,
args=args, kwargs=kwargs)
else:
cache_view_miss.send(cache=self, cache_key=cache_key,
args=args, kwargs=kwargs)

if not found:
rv = f(*args, **kwargs)

Expand Down Expand Up @@ -948,6 +965,14 @@ def decorated_function(*args, **kwargs):
logger.exception("Exception possibly due to cache backend.")
return f(*args, **kwargs)

if self.config["CACHE_ENABLE_SIGNALS"]:
if found:
cache_memoize_hit.send(cache=self, cache_key=cache_key,
f=f, args=args, kwargs=kwargs)
else:
cache_memoize_miss.send(cache=self, cache_key=cache_key,
f=f, args=args, kwargs=kwargs)

if not found:
rv = f(*args, **kwargs)

Expand Down