|
6 | 6 |
|
7 | 7 | """ |
8 | 8 |
|
| 9 | +import re |
9 | 10 | import typing |
10 | 11 | import warnings |
11 | 12 |
|
|
21 | 22 | __all__ = ("RedisBackend", "RedisSentinelBackend", "RedisClusterBackend") |
22 | 23 |
|
23 | 24 |
|
| 25 | +RE_VALID_PREFIX = re.compile(r"^[\w\-\.\:]{2,10}$") |
| 26 | + |
| 27 | + |
24 | 28 | class RedisBackend(BytesBackend): |
25 | 29 | r"""A `Redis <http://redis.io/>`__ backend, using the |
26 | 30 | `redis-py <http://pypi.python.org/pypi/redis/>`__ driver. |
@@ -87,6 +91,12 @@ class RedisBackend(BytesBackend): |
87 | 91 |
|
88 | 92 | .. versionadded:: 1.4.1 |
89 | 93 |
|
| 94 | + :param lock_prefix: string. This prefix is used for generating the name of |
| 95 | + locks. If customized, the prefix must be between 2 and 10 characters long, |
| 96 | + and may contain any alphanumeric character and the symbols "_-.:". |
| 97 | +
|
| 98 | + .. versionadded:: 1.5.0 |
| 99 | +
|
90 | 100 | :param socket_timeout: float, seconds for socket timeout. |
91 | 101 | Default is None (no timeout). |
92 | 102 |
|
@@ -132,6 +142,8 @@ class RedisBackend(BytesBackend): |
132 | 142 | .. versionadded:: 1.1.6 |
133 | 143 | """ |
134 | 144 |
|
| 145 | + lock_template: str = "_lock{0}" |
| 146 | + |
135 | 147 | def __init__(self, arguments): |
136 | 148 | arguments = arguments.copy() |
137 | 149 | self._imports() |
@@ -174,6 +186,16 @@ def __init__(self, arguments): |
174 | 186 | self.redis_expiration_time = arguments.pop("redis_expiration_time", 0) |
175 | 187 | self.connection_pool = arguments.pop("connection_pool", None) |
176 | 188 |
|
| 189 | + lock_prefix = arguments.pop("lock_prefix", None) |
| 190 | + if lock_prefix: |
| 191 | + if (not isinstance(lock_prefix, str)) or ( |
| 192 | + not RE_VALID_PREFIX.match(lock_prefix) |
| 193 | + ): |
| 194 | + raise ValueError( |
| 195 | + "Invalid `lock_prefix` submitted: `%s`." % lock_prefix |
| 196 | + ) |
| 197 | + self.lock_template = "%s{0}" % lock_prefix |
| 198 | + |
177 | 199 | self._create_client() |
178 | 200 |
|
179 | 201 | def _imports(self): |
@@ -225,7 +247,7 @@ def get_mutex(self, key): |
225 | 247 | if self.distributed_lock: |
226 | 248 | return _RedisLockWrapper( |
227 | 249 | self.writer_client.lock( |
228 | | - "_lock{0}".format(key), |
| 250 | + self.lock_template.format(key), |
229 | 251 | timeout=self.lock_timeout, |
230 | 252 | sleep=self.lock_sleep, |
231 | 253 | thread_local=self.thread_local_lock, |
|
0 commit comments