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