| 1 |
""" |
| 2 |
flask_caching.backends.rediscache |
| 3 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 4 |
|
| 5 |
The redis caching backend. |
| 6 |
|
| 7 |
:copyright: (c) 2018 by Peter Justin. |
| 8 |
:copyright: (c) 2010 by Thadeus Burgess. |
| 9 |
:license: BSD, see LICENSE for more details. |
| 10 |
""" |
| 11 |
|
| 12 |
from typing import Any |
| 13 |
|
| 14 |
from cachelib import RedisCache as CachelibRedisCache |
| 15 |
from flask import Flask |
| 16 |
|
| 17 |
from flask_caching.backends.base import BaseCache |
| 18 |
|
| 19 |
|
| 20 |
class RedisCache(BaseCache, CachelibRedisCache): |
| 21 |
"""Uses the Redis key-value store as a cache backend. |
| 22 |
|
| 23 |
The first argument can be either a string denoting address of the Redis |
| 24 |
server or an object resembling an instance of a redis.Redis class. |
| 25 |
|
| 26 |
Note: Python Redis API already takes care of encoding unicode strings on |
| 27 |
the fly. |
| 28 |
|
| 29 |
:param host: address of the Redis server or an object which API is |
| 30 |
compatible with the official Python Redis client (``redis-py``). |
| 31 |
:param port: port number on which Redis server listens for connections. |
| 32 |
:param password: password authentication for the Redis server. |
| 33 |
:param db: db (zero-based numeric index) on Redis Server to connect. |
| 34 |
:param default_timeout: the default timeout that is used if no timeout is |
| 35 |
specified on :meth:`~BaseCache.set`. A timeout of |
| 36 |
0 indicates that the cache never expires. |
| 37 |
:param key_prefix: A prefix that should be added to all keys. |
| 38 |
:param ignore_delete_many_errors: If set to ``False`` the ``delete_many`` |
| 39 |
method raises a ``RuntimeError`` in case |
| 40 |
a key couldn't be deleted. |
| 41 |
Defaults to ``False``. |
| 42 |
|
| 43 |
Any additional keyword arguments will be passed to ``redis.Redis``. |
| 44 |
""" |
| 45 |
|
| 46 |
def __init__( |
| 47 |
self, |
| 48 |
host: Any = "localhost", |
| 49 |
port: int = 6379, |
| 50 |
password: str | None = None, |
| 51 |
db: int = 0, |
| 52 |
default_timeout: int = 300, |
| 53 |
key_prefix: str | None = None, |
| 54 |
ignore_delete_many_errors: bool = False, |
| 55 |
**kwargs: Any, |
| 56 |
) -> None: |
| 57 |
CachelibRedisCache.__init__( |
| 58 |
self, |
| 59 |
host=host, |
| 60 |
port=port, |
| 61 |
password=password, |
| 62 |
db=db, |
| 63 |
default_timeout=default_timeout, |
| 64 |
key_prefix=key_prefix, |
| 65 |
ignore_delete_many_errors=ignore_delete_many_errors, |
| 66 |
**kwargs, |
| 67 |
) |
| 68 |
|
| 69 |
@classmethod |
| 70 |
def factory( |
| 71 |
cls, |
| 72 |
app: Flask, |
| 73 |
config: dict[str, Any], |
| 74 |
args: list[Any], |
| 75 |
kwargs: dict[str, Any], |
| 76 |
) -> "RedisCache": |
| 77 |
try: |
| 78 |
from redis import from_url as redis_from_url |
| 79 |
except ImportError as e: |
| 80 |
raise RuntimeError("no redis module found") from e |
| 81 |
|
| 82 |
kwargs.update( |
| 83 |
dict( |
| 84 |
host=config.get("CACHE_REDIS_HOST", "localhost"), |
| 85 |
port=config.get("CACHE_REDIS_PORT", 6379), |
| 86 |
db=config.get("CACHE_REDIS_DB", 0), |
| 87 |
) |
| 88 |
) |
| 89 |
password = config.get("CACHE_REDIS_PASSWORD") |
| 90 |
if password: |
| 91 |
kwargs["password"] = password |
| 92 |
|
| 93 |
key_prefix = config.get("CACHE_KEY_PREFIX") |
| 94 |
if key_prefix: |
| 95 |
kwargs["key_prefix"] = key_prefix |
| 96 |
|
| 97 |
redis_url = config.get("CACHE_REDIS_URL") |
| 98 |
if redis_url: |
| 99 |
redis_kwargs = config.pop("CACHE_OPTIONS", None) or {} |
| 100 |
kwargs["host"] = redis_from_url( |
| 101 |
redis_url, db=kwargs.pop("db", None), **redis_kwargs |
| 102 |
) |
| 103 |
|
| 104 |
new_class = cls(*args, **kwargs) |
| 105 |
|
| 106 |
return new_class |
| 107 |
|
| 108 |
def unlink(self, *keys: str) -> Any: |
| 109 |
"""when redis-py >= 3.0.0 and redis > 4, support this operation""" |
| 110 |
if not keys: |
| 111 |
return None |
| 112 |
prefix = self._get_prefix() |
| 113 |
if prefix: |
| 114 |
keys = tuple(prefix + key for key in keys) |
| 115 |
|
| 116 |
unlink = getattr(self._write_client, "unlink", None) |
| 117 |
if unlink is not None and callable(unlink): |
| 118 |
return self._write_client.unlink(*keys) |
| 119 |
return self._write_client.delete(*keys) |
| 120 |
|
| 121 |
|
| 122 |
class RedisSentinelCache(RedisCache): |
| 123 |
"""Uses the Redis key-value store as a cache backend. |
| 124 |
|
| 125 |
The first argument can be either a string denoting address of the Redis |
| 126 |
server or an object resembling an instance of a redis.Redis class. |
| 127 |
|
| 128 |
Note: Python Redis API already takes care of encoding unicode strings on |
| 129 |
the fly. |
| 130 |
|
| 131 |
|
| 132 |
:param sentinels: A list or a tuple of Redis sentinel addresses. |
| 133 |
:param master: The name of the master server in a sentinel configuration. |
| 134 |
:param password: password authentication for the Redis server. |
| 135 |
:param db: db (zero-based numeric index) on Redis Server to connect. |
| 136 |
:param default_timeout: the default timeout that is used if no timeout is |
| 137 |
specified on :meth:`~BaseCache.set`. A timeout of |
| 138 |
0 indicates that the cache never expires. |
| 139 |
:param key_prefix: A prefix that should be added to all keys. |
| 140 |
:param ignore_delete_many_errors: If set to ``False`` the ``delete_many`` |
| 141 |
method raises a ``RuntimeError`` in case |
| 142 |
a key couldn't be deleted. |
| 143 |
Defaults to ``False``. |
| 144 |
|
| 145 |
Any additional keyword arguments will be passed to |
| 146 |
``redis.sentinel.Sentinel``. |
| 147 |
""" |
| 148 |
|
| 149 |
def __init__( |
| 150 |
self, |
| 151 |
sentinels: Any = None, |
| 152 |
master: str = "mymaster", |
| 153 |
password: str | None = None, |
| 154 |
db: int = 0, |
| 155 |
default_timeout: int = 300, |
| 156 |
key_prefix: str = "", |
| 157 |
ignore_delete_many_errors: bool = False, |
| 158 |
**kwargs: Any, |
| 159 |
) -> None: |
| 160 |
try: |
| 161 |
import redis.sentinel |
| 162 |
except ImportError as e: |
| 163 |
raise RuntimeError("no redis module found") from e |
| 164 |
|
| 165 |
if kwargs.get("decode_responses", None): |
| 166 |
raise ValueError("decode_responses is not supported by RedisCache.") |
| 167 |
|
| 168 |
sentinels = sentinels or [("127.0.0.1", 26379)] |
| 169 |
sentinel_kwargs = { |
| 170 |
key[9:]: value |
| 171 |
for key, value in kwargs.items() |
| 172 |
if key.startswith("sentinel_") |
| 173 |
} |
| 174 |
kwargs = { |
| 175 |
key: value |
| 176 |
for key, value in kwargs.items() |
| 177 |
if not key.startswith("sentinel_") |
| 178 |
} |
| 179 |
|
| 180 |
sentinel = redis.sentinel.Sentinel( |
| 181 |
sentinels=sentinels, |
| 182 |
password=password, |
| 183 |
db=db, |
| 184 |
sentinel_kwargs=sentinel_kwargs, |
| 185 |
**kwargs, |
| 186 |
) |
| 187 |
|
| 188 |
write_client = sentinel.master_for(master) |
| 189 |
read_client = sentinel.slave_for(master) |
| 190 |
|
| 191 |
super().__init__( |
| 192 |
host=write_client, |
| 193 |
key_prefix=key_prefix, |
| 194 |
default_timeout=default_timeout, |
| 195 |
ignore_delete_many_errors=ignore_delete_many_errors, |
| 196 |
) |
| 197 |
|
| 198 |
self._read_client = read_client |
| 199 |
|
| 200 |
@classmethod |
| 201 |
def factory( |
| 202 |
cls, |
| 203 |
app: Flask, |
| 204 |
config: dict[str, Any], |
| 205 |
args: list[Any], |
| 206 |
kwargs: dict[str, Any], |
| 207 |
) -> "RedisSentinelCache": |
| 208 |
kwargs.update( |
| 209 |
dict( |
| 210 |
sentinels=config.get("CACHE_REDIS_SENTINELS", [("127.0.0.1", 26379)]), |
| 211 |
master=config.get("CACHE_REDIS_SENTINEL_MASTER", "mymaster"), |
| 212 |
password=config.get("CACHE_REDIS_PASSWORD", None), |
| 213 |
sentinel_password=config.get("CACHE_REDIS_SENTINEL_PASSWORD", None), |
| 214 |
key_prefix=config.get("CACHE_KEY_PREFIX", None), |
| 215 |
db=config.get("CACHE_REDIS_DB", 0), |
| 216 |
) |
| 217 |
) |
| 218 |
|
| 219 |
return cls(*args, **kwargs) |
| 220 |
|
| 221 |
|
| 222 |
class RedisClusterCache(RedisCache): |
| 223 |
"""Uses the Redis key-value store as a cache backend. |
| 224 |
|
| 225 |
The first argument can be either a string denoting address of the Redis |
| 226 |
server or an object resembling an instance of a rediscluster.RedisCluster |
| 227 |
class. |
| 228 |
|
| 229 |
Note: Python Redis API already takes care of encoding unicode strings on |
| 230 |
the fly. |
| 231 |
|
| 232 |
|
| 233 |
:param cluster: The redis cluster nodes address separated by comma. |
| 234 |
e.g. host1:port1,host2:port2,host3:port3 . |
| 235 |
:param password: password authentication for the Redis server. |
| 236 |
:param default_timeout: the default timeout that is used if no timeout is |
| 237 |
specified on :meth:`~BaseCache.set`. A timeout of |
| 238 |
0 indicates that the cache never expires. |
| 239 |
:param key_prefix: A prefix that should be added to all keys. |
| 240 |
:param ignore_delete_many_errors: If set to ``False`` the ``delete_many`` |
| 241 |
method raises a ``RuntimeError`` in case |
| 242 |
a key couldn't be deleted. |
| 243 |
Defaults to ``False``. |
| 244 |
|
| 245 |
Any additional keyword arguments will be passed to |
| 246 |
``rediscluster.RedisCluster``. |
| 247 |
""" |
| 248 |
|
| 249 |
def __init__( |
| 250 |
self, |
| 251 |
cluster: Any = "", |
| 252 |
password: str = "", |
| 253 |
default_timeout: int = 300, |
| 254 |
key_prefix: str = "", |
| 255 |
ignore_delete_many_errors: bool = False, |
| 256 |
**kwargs: Any, |
| 257 |
) -> None: |
| 258 |
if kwargs.get("decode_responses", None): |
| 259 |
raise ValueError("decode_responses is not supported by RedisCache.") |
| 260 |
|
| 261 |
try: |
| 262 |
from redis import RedisCluster |
| 263 |
from redis.cluster import ClusterNode |
| 264 |
except ImportError as e: |
| 265 |
raise RuntimeError("no redis.cluster module found") from e |
| 266 |
|
| 267 |
redis_url = kwargs.pop("redis_url", None) |
| 268 |
|
| 269 |
# Use URL-based connection if provided, otherwise use startup nodes. |
| 270 |
if redis_url: |
| 271 |
cluster = RedisCluster.from_url(redis_url, **kwargs) |
| 272 |
else: |
| 273 |
try: |
| 274 |
nodes = [(node.split(":")) for node in cluster.split(",")] |
| 275 |
startup_nodes = [ |
| 276 |
ClusterNode(node[0].strip(), int(node[1].strip())) for node in nodes |
| 277 |
] |
| 278 |
except IndexError as e: |
| 279 |
raise ValueError( |
| 280 |
"Please give the correct cluster argument " |
| 281 |
"e.g. host1:port1,host2:port2,host3:port3" |
| 282 |
) from e |
| 283 |
|
| 284 |
# Skips the check of cluster-require-full-coverage config, |
| 285 |
# useful for clusters without the CONFIG command (like aws) |
| 286 |
skip_full_coverage_check = kwargs.pop("skip_full_coverage_check", True) |
| 287 |
|
| 288 |
cluster = RedisCluster( |
| 289 |
startup_nodes=startup_nodes, |
| 290 |
password=password, |
| 291 |
skip_full_coverage_check=skip_full_coverage_check, |
| 292 |
**kwargs, |
| 293 |
) |
| 294 |
|
| 295 |
super().__init__( |
| 296 |
host=cluster, |
| 297 |
key_prefix=key_prefix, |
| 298 |
default_timeout=default_timeout, |
| 299 |
ignore_delete_many_errors=ignore_delete_many_errors, |
| 300 |
) |
| 301 |
|
| 302 |
@classmethod |
| 303 |
def factory( |
| 304 |
cls, |
| 305 |
app: Flask, |
| 306 |
config: dict[str, Any], |
| 307 |
args: list[Any], |
| 308 |
kwargs: dict[str, Any], |
| 309 |
) -> "RedisClusterCache": |
| 310 |
kwargs.update( |
| 311 |
dict( |
| 312 |
cluster=config.get("CACHE_REDIS_CLUSTER", ""), |
| 313 |
password=config.get("CACHE_REDIS_PASSWORD", ""), |
| 314 |
default_timeout=config.get("CACHE_DEFAULT_TIMEOUT", 300), |
| 315 |
key_prefix=config.get("CACHE_KEY_PREFIX", ""), |
| 316 |
redis_url=config.get("CACHE_REDIS_URL", ""), |
| 317 |
) |
| 318 |
) |
| 319 |
return cls(*args, **kwargs) |