| 1 |
Metadata-Version: 2.1 |
| 2 |
Name: django-redis |
| 3 |
Version: 5.4.0 |
| 4 |
Summary: Full featured redis cache backend for Django. |
| 5 |
Home-page: https://github.com/jazzband/django-redis |
| 6 |
Author: Andrei Antoukh |
| 7 |
Author-email: [email protected] |
| 8 |
License: BSD-3-Clause |
| 9 |
Classifier: Development Status :: 5 - Production/Stable |
| 10 |
Classifier: Environment :: Web Environment |
| 11 |
Classifier: Framework :: Django |
| 12 |
Classifier: Framework :: Django :: 3.2 |
| 13 |
Classifier: Framework :: Django :: 4.0 |
| 14 |
Classifier: Framework :: Django :: 4.1 |
| 15 |
Classifier: Framework :: Django :: 4.2 |
| 16 |
Classifier: Intended Audience :: Developers |
| 17 |
Classifier: License :: OSI Approved :: BSD License |
| 18 |
Classifier: Operating System :: OS Independent |
| 19 |
Classifier: Programming Language :: Python |
| 20 |
Classifier: Programming Language :: Python :: 3 |
| 21 |
Classifier: Programming Language :: Python :: 3 :: Only |
| 22 |
Classifier: Programming Language :: Python :: 3.6 |
| 23 |
Classifier: Programming Language :: Python :: 3.7 |
| 24 |
Classifier: Programming Language :: Python :: 3.8 |
| 25 |
Classifier: Programming Language :: Python :: 3.9 |
| 26 |
Classifier: Programming Language :: Python :: 3.10 |
| 27 |
Classifier: Programming Language :: Python :: 3.11 |
| 28 |
Classifier: Topic :: Software Development :: Libraries |
| 29 |
Classifier: Topic :: Utilities |
| 30 |
Requires-Python: >=3.6 |
| 31 |
Description-Content-Type: text/x-rst |
| 32 |
License-File: LICENSE |
| 33 |
License-File: AUTHORS.rst |
| 34 |
Requires-Dist: Django>=3.2 |
| 35 |
Requires-Dist: redis!=4.0.0,!=4.0.1,>=3 |
| 36 |
Provides-Extra: hiredis |
| 37 |
Requires-Dist: redis[hiredis]!=4.0.0,!=4.0.1,>=3; extra == "hiredis" |
| 38 |
|
| 39 |
============================== |
| 40 |
Redis cache backend for Django |
| 41 |
============================== |
| 42 |
|
| 43 |
.. image:: https://jazzband.co/static/img/badge.svg |
| 44 |
:target: https://jazzband.co/ |
| 45 |
:alt: Jazzband |
| 46 |
|
| 47 |
.. image:: https://github.com/jazzband/django-redis/actions/workflows/ci.yml/badge.svg |
| 48 |
:target: https://github.com/jazzband/django-redis/actions/workflows/ci.yml |
| 49 |
:alt: GitHub Actions |
| 50 |
|
| 51 |
.. image:: https://codecov.io/gh/jazzband/django-redis/branch/master/graph/badge.svg |
| 52 |
:target: https://codecov.io/gh/jazzband/django-redis |
| 53 |
:alt: Coverage |
| 54 |
|
| 55 |
.. image:: https://img.shields.io/pypi/v/django-redis.svg?style=flat |
| 56 |
:target: https://pypi.org/project/django-redis/ |
| 57 |
|
| 58 |
This is a `Jazzband <https://jazzband.co>`_ project. By contributing you agree |
| 59 |
to abide by the `Contributor Code of Conduct |
| 60 |
<https://jazzband.co/about/conduct>`_ and follow the `guidelines |
| 61 |
<https://jazzband.co/about/guidelines>`_. |
| 62 |
|
| 63 |
Introduction |
| 64 |
------------ |
| 65 |
|
| 66 |
django-redis is a BSD licensed, full featured Redis cache and session backend |
| 67 |
for Django. |
| 68 |
|
| 69 |
Why use django-redis? |
| 70 |
~~~~~~~~~~~~~~~~~~~~~ |
| 71 |
|
| 72 |
- Uses native redis-py url notation connection strings |
| 73 |
- Pluggable clients |
| 74 |
- Pluggable parsers |
| 75 |
- Pluggable serializers |
| 76 |
- Primary/secondary support in the default client |
| 77 |
- Comprehensive test suite |
| 78 |
- Used in production in several projects as cache and session storage |
| 79 |
- Supports infinite timeouts |
| 80 |
- Facilities for raw access to Redis client/connection pool |
| 81 |
- Highly configurable (can emulate memcached exception behavior, for example) |
| 82 |
- Unix sockets supported by default |
| 83 |
|
| 84 |
Requirements |
| 85 |
~~~~~~~~~~~~ |
| 86 |
|
| 87 |
- `Python`_ 3.6+ |
| 88 |
- `Django`_ 2.2+ |
| 89 |
- `redis-py`_ 3.0+ |
| 90 |
- `Redis server`_ 2.8+ |
| 91 |
|
| 92 |
.. _Python: https://www.python.org/downloads/ |
| 93 |
.. _Django: https://www.djangoproject.com/download/ |
| 94 |
.. _redis-py: https://pypi.org/project/redis/ |
| 95 |
.. _Redis server: https://redis.io/download |
| 96 |
|
| 97 |
User guide |
| 98 |
---------- |
| 99 |
|
| 100 |
Installation |
| 101 |
~~~~~~~~~~~~ |
| 102 |
|
| 103 |
Install with pip: |
| 104 |
|
| 105 |
.. code-block:: console |
| 106 |
|
| 107 |
$ python -m pip install django-redis |
| 108 |
|
| 109 |
Configure as cache backend |
| 110 |
~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 111 |
|
| 112 |
To start using django-redis, you should change your Django cache settings to |
| 113 |
something like: |
| 114 |
|
| 115 |
.. code-block:: python |
| 116 |
|
| 117 |
CACHES = { |
| 118 |
"default": { |
| 119 |
"BACKEND": "django_redis.cache.RedisCache", |
| 120 |
"LOCATION": "redis://127.0.0.1:6379/1", |
| 121 |
"OPTIONS": { |
| 122 |
"CLIENT_CLASS": "django_redis.client.DefaultClient", |
| 123 |
} |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
django-redis uses the redis-py native URL notation for connection strings, it |
| 128 |
allows better interoperability and has a connection string in more "standard" |
| 129 |
way. Some examples: |
| 130 |
|
| 131 |
- ``redis://[[username]:[password]]@localhost:6379/0`` |
| 132 |
- ``rediss://[[username]:[password]]@localhost:6379/0`` |
| 133 |
- ``unix://[[username]:[password]]@/path/to/socket.sock?db=0`` |
| 134 |
|
| 135 |
Three URL schemes are supported: |
| 136 |
|
| 137 |
- ``redis://``: creates a normal TCP socket connection |
| 138 |
- ``rediss://``: creates a SSL wrapped TCP socket connection |
| 139 |
- ``unix://`` creates a Unix Domain Socket connection |
| 140 |
|
| 141 |
There are several ways to specify a database number: |
| 142 |
|
| 143 |
- A ``db`` querystring option, e.g. ``redis://localhost?db=0`` |
| 144 |
- If using the ``redis://`` scheme, the path argument of the URL, e.g. |
| 145 |
``redis://localhost/0`` |
| 146 |
|
| 147 |
When using `Redis' ACLs <https://redis.io/topics/acl>`_, you will need to add the |
| 148 |
username to the URL (and provide the password with the Cache ``OPTIONS``). |
| 149 |
The login for the user ``django`` would look like this: |
| 150 |
|
| 151 |
.. code-block:: python |
| 152 |
|
| 153 |
CACHES = { |
| 154 |
"default": { |
| 155 |
"BACKEND": "django_redis.cache.RedisCache", |
| 156 |
"LOCATION": "redis://django@localhost:6379/0", |
| 157 |
"OPTIONS": { |
| 158 |
"CLIENT_CLASS": "django_redis.client.DefaultClient", |
| 159 |
"PASSWORD": "mysecret" |
| 160 |
} |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
An alternative would be write both username and password into the URL: |
| 165 |
|
| 166 |
.. code-block:: python |
| 167 |
|
| 168 |
CACHES = { |
| 169 |
"default": { |
| 170 |
"BACKEND": "django_redis.cache.RedisCache", |
| 171 |
"LOCATION": "redis://django:mysecret@localhost:6379/0", |
| 172 |
"OPTIONS": { |
| 173 |
"CLIENT_CLASS": "django_redis.client.DefaultClient", |
| 174 |
} |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
In some circumstances the password you should use to connect Redis |
| 179 |
is not URL-safe, in this case you can escape it or just use the |
| 180 |
convenience option in ``OPTIONS`` dict: |
| 181 |
|
| 182 |
.. code-block:: python |
| 183 |
|
| 184 |
CACHES = { |
| 185 |
"default": { |
| 186 |
"BACKEND": "django_redis.cache.RedisCache", |
| 187 |
"LOCATION": "redis://127.0.0.1:6379/1", |
| 188 |
"OPTIONS": { |
| 189 |
"CLIENT_CLASS": "django_redis.client.DefaultClient", |
| 190 |
"PASSWORD": "mysecret" |
| 191 |
} |
| 192 |
} |
| 193 |
} |
| 194 |
|
| 195 |
Take care, that this option does not overwrites the password in the uri, so if |
| 196 |
you have set the password in the uri, this settings will be ignored. |
| 197 |
|
| 198 |
Configure as session backend |
| 199 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 200 |
|
| 201 |
Django can by default use any cache backend as session backend and you benefit |
| 202 |
from that by using django-redis as backend for session storage without |
| 203 |
installing any additional backends: |
| 204 |
|
| 205 |
.. code-block:: python |
| 206 |
|
| 207 |
SESSION_ENGINE = "django.contrib.sessions.backends.cache" |
| 208 |
SESSION_CACHE_ALIAS = "default" |
| 209 |
|
| 210 |
Testing with django-redis |
| 211 |
~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 212 |
|
| 213 |
django-redis supports customizing the underlying Redis client (see "Pluggable |
| 214 |
clients"). This can be used for testing purposes. |
| 215 |
|
| 216 |
In case you want to flush all data from the cache after a test, add the |
| 217 |
following lines to your test class: |
| 218 |
|
| 219 |
.. code-block:: python |
| 220 |
|
| 221 |
from django_redis import get_redis_connection |
| 222 |
|
| 223 |
def tearDown(self): |
| 224 |
get_redis_connection("default").flushall() |
| 225 |
|
| 226 |
Advanced usage |
| 227 |
-------------- |
| 228 |
|
| 229 |
Pickle version |
| 230 |
~~~~~~~~~~~~~~ |
| 231 |
|
| 232 |
For almost all values, django-redis uses pickle to serialize objects. |
| 233 |
|
| 234 |
The ``pickle.DEFAULT_PROTOCOL`` version of pickle is used by default to ensure safe upgrades and compatibility across Python versions. |
| 235 |
If you want set a concrete version, you can do it, using ``PICKLE_VERSION`` option: |
| 236 |
|
| 237 |
.. code-block:: python |
| 238 |
|
| 239 |
CACHES = { |
| 240 |
"default": { |
| 241 |
# ... |
| 242 |
"OPTIONS": { |
| 243 |
"PICKLE_VERSION": -1 # Will use highest protocol version available |
| 244 |
} |
| 245 |
} |
| 246 |
} |
| 247 |
|
| 248 |
Socket timeout |
| 249 |
~~~~~~~~~~~~~~ |
| 250 |
|
| 251 |
Socket timeout can be set using ``SOCKET_TIMEOUT`` and |
| 252 |
``SOCKET_CONNECT_TIMEOUT`` options: |
| 253 |
|
| 254 |
.. code-block:: python |
| 255 |
|
| 256 |
CACHES = { |
| 257 |
"default": { |
| 258 |
# ... |
| 259 |
"OPTIONS": { |
| 260 |
"SOCKET_CONNECT_TIMEOUT": 5, # seconds |
| 261 |
"SOCKET_TIMEOUT": 5, # seconds |
| 262 |
} |
| 263 |
} |
| 264 |
} |
| 265 |
|
| 266 |
``SOCKET_CONNECT_TIMEOUT`` is the timeout for the connection to be established |
| 267 |
and ``SOCKET_TIMEOUT`` is the timeout for read and write operations after the |
| 268 |
connection is established. |
| 269 |
|
| 270 |
Compression support |
| 271 |
~~~~~~~~~~~~~~~~~~~ |
| 272 |
|
| 273 |
django-redis comes with compression support out of the box, but is deactivated |
| 274 |
by default. You can activate it setting up a concrete backend: |
| 275 |
|
| 276 |
.. code-block:: python |
| 277 |
|
| 278 |
CACHES = { |
| 279 |
"default": { |
| 280 |
# ... |
| 281 |
"OPTIONS": { |
| 282 |
"COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor", |
| 283 |
} |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
Let see an example, of how make it work with *lzma* compression format: |
| 288 |
|
| 289 |
.. code-block:: python |
| 290 |
|
| 291 |
import lzma |
| 292 |
|
| 293 |
CACHES = { |
| 294 |
"default": { |
| 295 |
# ... |
| 296 |
"OPTIONS": { |
| 297 |
"COMPRESSOR": "django_redis.compressors.lzma.LzmaCompressor", |
| 298 |
} |
| 299 |
} |
| 300 |
} |
| 301 |
|
| 302 |
*Lz4* compression support (requires the lz4 library): |
| 303 |
|
| 304 |
.. code-block:: python |
| 305 |
|
| 306 |
import lz4 |
| 307 |
|
| 308 |
CACHES = { |
| 309 |
"default": { |
| 310 |
# ... |
| 311 |
"OPTIONS": { |
| 312 |
"COMPRESSOR": "django_redis.compressors.lz4.Lz4Compressor", |
| 313 |
} |
| 314 |
} |
| 315 |
} |
| 316 |
|
| 317 |
*Zstandard (zstd)* compression support (requires the pyzstd library): |
| 318 |
|
| 319 |
.. code-block:: python |
| 320 |
|
| 321 |
import pyzstd |
| 322 |
|
| 323 |
CACHES = { |
| 324 |
"default": { |
| 325 |
# ... |
| 326 |
"OPTIONS": { |
| 327 |
"COMPRESSOR": "django_redis.compressors.zstd.ZStdCompressor", |
| 328 |
} |
| 329 |
} |
| 330 |
} |
| 331 |
|
| 332 |
Memcached exceptions behavior |
| 333 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 334 |
|
| 335 |
In some situations, when Redis is only used for cache, you do not want |
| 336 |
exceptions when Redis is down. This is default behavior in the memcached |
| 337 |
backend and it can be emulated in django-redis. |
| 338 |
|
| 339 |
For setup memcached like behaviour (ignore connection exceptions), you should |
| 340 |
set ``IGNORE_EXCEPTIONS`` settings on your cache configuration: |
| 341 |
|
| 342 |
.. code-block:: python |
| 343 |
|
| 344 |
CACHES = { |
| 345 |
"default": { |
| 346 |
# ... |
| 347 |
"OPTIONS": { |
| 348 |
"IGNORE_EXCEPTIONS": True, |
| 349 |
} |
| 350 |
} |
| 351 |
} |
| 352 |
|
| 353 |
Also, you can apply the same settings to all configured caches, you can set the global flag in |
| 354 |
your settings: |
| 355 |
|
| 356 |
.. code-block:: python |
| 357 |
|
| 358 |
DJANGO_REDIS_IGNORE_EXCEPTIONS = True |
| 359 |
|
| 360 |
Log Ignored Exceptions |
| 361 |
~~~~~~~~~~~~~~~~~~~~~~ |
| 362 |
|
| 363 |
When ignoring exceptions with ``IGNORE_EXCEPTIONS`` or |
| 364 |
``DJANGO_REDIS_IGNORE_EXCEPTIONS``, you may optionally log exceptions using the |
| 365 |
global variable ``DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS`` in your settings file:: |
| 366 |
|
| 367 |
DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS = True |
| 368 |
|
| 369 |
If you wish to specify the logger in which the exceptions are output, simply |
| 370 |
set the global variable ``DJANGO_REDIS_LOGGER`` to the string name and/or path |
| 371 |
of the desired logger. This will default to ``__name__`` if no logger is |
| 372 |
specified and ``DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS`` is ``True``:: |
| 373 |
|
| 374 |
DJANGO_REDIS_LOGGER = 'some.specified.logger' |
| 375 |
|
| 376 |
Infinite timeout |
| 377 |
~~~~~~~~~~~~~~~~ |
| 378 |
|
| 379 |
django-redis comes with infinite timeouts support out of the box. And it |
| 380 |
behaves in same way as django backend contract specifies: |
| 381 |
|
| 382 |
- ``timeout=0`` expires the value immediately. |
| 383 |
- ``timeout=None`` infinite timeout |
| 384 |
|
| 385 |
.. code-block:: python |
| 386 |
|
| 387 |
cache.set("key", "value", timeout=None) |
| 388 |
|
| 389 |
Get ttl (time-to-live) from key |
| 390 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 391 |
|
| 392 |
With Redis, you can access to ttl of any stored key, for it, django-redis |
| 393 |
exposes ``ttl`` function. |
| 394 |
|
| 395 |
It returns: |
| 396 |
|
| 397 |
- 0 if key does not exists (or already expired). |
| 398 |
- None for keys that exists but does not have any expiration. |
| 399 |
- ttl value for any volatile key (any key that has expiration). |
| 400 |
|
| 401 |
.. code-block:: pycon |
| 402 |
|
| 403 |
>>> from django.core.cache import cache |
| 404 |
>>> cache.set("foo", "value", timeout=25) |
| 405 |
>>> cache.ttl("foo") |
| 406 |
25 |
| 407 |
>>> cache.ttl("not-existent") |
| 408 |
0 |
| 409 |
|
| 410 |
With Redis, you can access to ttl of any stored key in milliseconds, for it, django-redis |
| 411 |
exposes ``pttl`` function. |
| 412 |
|
| 413 |
.. code-block:: pycon |
| 414 |
|
| 415 |
>>> from django.core.cache import cache |
| 416 |
>>> cache.set("foo", "value", timeout=25) |
| 417 |
>>> cache.pttl("foo") |
| 418 |
25000 |
| 419 |
>>> cache.pttl("not-existent") |
| 420 |
0 |
| 421 |
|
| 422 |
Expire & Persist |
| 423 |
~~~~~~~~~~~~~~~~ |
| 424 |
|
| 425 |
Additionally to the simple ttl query, you can send persist a concrete key or |
| 426 |
specify a new expiration timeout using the ``persist`` and ``expire`` methods: |
| 427 |
|
| 428 |
.. code-block:: pycon |
| 429 |
|
| 430 |
>>> cache.set("foo", "bar", timeout=22) |
| 431 |
>>> cache.ttl("foo") |
| 432 |
22 |
| 433 |
>>> cache.persist("foo") |
| 434 |
True |
| 435 |
>>> cache.ttl("foo") |
| 436 |
None |
| 437 |
|
| 438 |
.. code-block:: pycon |
| 439 |
|
| 440 |
>>> cache.set("foo", "bar", timeout=22) |
| 441 |
>>> cache.expire("foo", timeout=5) |
| 442 |
True |
| 443 |
>>> cache.ttl("foo") |
| 444 |
5 |
| 445 |
|
| 446 |
The ``expire_at`` method can be used to make the key expire at a specific moment in time. |
| 447 |
|
| 448 |
.. code-block:: pycon |
| 449 |
|
| 450 |
>>> cache.set("foo", "bar", timeout=22) |
| 451 |
>>> cache.expire_at("foo", datetime.now() + timedelta(hours=1)) |
| 452 |
True |
| 453 |
>>> cache.ttl("foo") |
| 454 |
3600 |
| 455 |
|
| 456 |
The ``pexpire_at`` method can be used to make the key expire at a specific moment in time with milliseconds precision: |
| 457 |
|
| 458 |
.. code-block:: pycon |
| 459 |
|
| 460 |
>>> cache.set("foo", "bar", timeout=22) |
| 461 |
>>> cache.pexpire_at("foo", datetime.now() + timedelta(milliseconds=900, hours=1)) |
| 462 |
True |
| 463 |
>>> cache.ttl("foo") |
| 464 |
3601 |
| 465 |
>>> cache.pttl("foo") |
| 466 |
3600900 |
| 467 |
|
| 468 |
The ``pexpire`` method can be used to provide millisecond precision: |
| 469 |
|
| 470 |
.. code-block:: pycon |
| 471 |
|
| 472 |
>>> cache.set("foo", "bar", timeout=22) |
| 473 |
>>> cache.pexpire("foo", timeout=5500) |
| 474 |
True |
| 475 |
>>> cache.pttl("foo") |
| 476 |
5500 |
| 477 |
|
| 478 |
Locks |
| 479 |
~~~~~ |
| 480 |
|
| 481 |
It also supports the Redis ability to create Redis distributed named locks. The |
| 482 |
Lock interface is identical to the ``threading.Lock`` so you can use it as |
| 483 |
replacement. |
| 484 |
|
| 485 |
.. code-block:: python |
| 486 |
|
| 487 |
with cache.lock("somekey"): |
| 488 |
do_some_thing() |
| 489 |
|
| 490 |
Scan & Delete keys in bulk |
| 491 |
~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 492 |
|
| 493 |
django-redis comes with some additional methods that help with searching or |
| 494 |
deleting keys using glob patterns. |
| 495 |
|
| 496 |
.. code-block:: pycon |
| 497 |
|
| 498 |
>>> from django.core.cache import cache |
| 499 |
>>> cache.keys("foo_*") |
| 500 |
["foo_1", "foo_2"] |
| 501 |
|
| 502 |
A simple search like this will return all matched values. In databases with a |
| 503 |
large number of keys this isn't suitable method. Instead, you can use the |
| 504 |
``iter_keys`` function that works like the ``keys`` function but uses Redis |
| 505 |
server side cursors. Calling ``iter_keys`` will return a generator that you can |
| 506 |
then iterate over efficiently. |
| 507 |
|
| 508 |
.. code-block:: pycon |
| 509 |
|
| 510 |
>>> from django.core.cache import cache |
| 511 |
>>> cache.iter_keys("foo_*") |
| 512 |
<generator object algo at 0x7ffa9c2713a8> |
| 513 |
>>> next(cache.iter_keys("foo_*")) |
| 514 |
"foo_1" |
| 515 |
|
| 516 |
For deleting keys, you should use ``delete_pattern`` which has the same glob |
| 517 |
pattern syntax as the ``keys`` function and returns the number of deleted keys. |
| 518 |
|
| 519 |
.. code-block:: pycon |
| 520 |
|
| 521 |
>>> from django.core.cache import cache |
| 522 |
>>> cache.delete_pattern("foo_*") |
| 523 |
|
| 524 |
To achieve the best performance while deleting many keys, you should set ``DJANGO_REDIS_SCAN_ITERSIZE`` to a relatively |
| 525 |
high number (e.g., 100_000) by default in Django settings or pass it directly to the ``delete_pattern``. |
| 526 |
|
| 527 |
|
| 528 |
.. code-block:: pycon |
| 529 |
|
| 530 |
>>> from django.core.cache import cache |
| 531 |
>>> cache.delete_pattern("foo_*", itersize=100_000) |
| 532 |
|
| 533 |
Redis native commands |
| 534 |
~~~~~~~~~~~~~~~~~~~~~ |
| 535 |
|
| 536 |
django-redis has limited support for some Redis atomic operations, such as the |
| 537 |
commands ``SETNX`` and ``INCR``. |
| 538 |
|
| 539 |
You can use the ``SETNX`` command through the backend ``set()`` method with the |
| 540 |
``nx`` parameter: |
| 541 |
|
| 542 |
.. code-block:: pycon |
| 543 |
|
| 544 |
>>> from django.core.cache import cache |
| 545 |
>>> cache.set("key", "value1", nx=True) |
| 546 |
True |
| 547 |
>>> cache.set("key", "value2", nx=True) |
| 548 |
False |
| 549 |
>>> cache.get("key") |
| 550 |
"value1" |
| 551 |
|
| 552 |
Also, the ``incr`` and ``decr`` methods use Redis atomic operations when the |
| 553 |
value that a key contains is suitable for it. |
| 554 |
|
| 555 |
Raw client access |
| 556 |
~~~~~~~~~~~~~~~~~ |
| 557 |
|
| 558 |
In some situations your application requires access to a raw Redis client to |
| 559 |
use some advanced features that aren't exposed by the Django cache interface. |
| 560 |
To avoid storing another setting for creating a raw connection, django-redis |
| 561 |
exposes functions with which you can obtain a raw client reusing the cache |
| 562 |
connection string: ``get_redis_connection(alias)``. |
| 563 |
|
| 564 |
.. code-block:: pycon |
| 565 |
|
| 566 |
>>> from django_redis import get_redis_connection |
| 567 |
>>> con = get_redis_connection("default") |
| 568 |
>>> con |
| 569 |
<redis.client.Redis object at 0x2dc4510> |
| 570 |
|
| 571 |
WARNING: Not all pluggable clients support this feature. |
| 572 |
|
| 573 |
Connection pools |
| 574 |
~~~~~~~~~~~~~~~~ |
| 575 |
|
| 576 |
Behind the scenes, django-redis uses the underlying redis-py connection pool |
| 577 |
implementation, and exposes a simple way to configure it. Alternatively, you |
| 578 |
can directly customize a connection/connection pool creation for a backend. |
| 579 |
|
| 580 |
The default redis-py behavior is to not close connections, recycling them when |
| 581 |
possible. |
| 582 |
|
| 583 |
Configure default connection pool |
| 584 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 585 |
|
| 586 |
The default connection pool is simple. For example, you can customize the |
| 587 |
maximum number of connections in the pool by setting ``CONNECTION_POOL_KWARGS`` |
| 588 |
in the ``CACHES`` setting: |
| 589 |
|
| 590 |
.. code-block:: python |
| 591 |
|
| 592 |
CACHES = { |
| 593 |
"default": { |
| 594 |
"BACKEND": "django_redis.cache.RedisCache", |
| 595 |
# ... |
| 596 |
"OPTIONS": { |
| 597 |
"CONNECTION_POOL_KWARGS": {"max_connections": 100} |
| 598 |
} |
| 599 |
} |
| 600 |
} |
| 601 |
|
| 602 |
You can verify how many connections the pool has opened with the following |
| 603 |
snippet: |
| 604 |
|
| 605 |
.. code-block:: python |
| 606 |
|
| 607 |
from django_redis import get_redis_connection |
| 608 |
|
| 609 |
r = get_redis_connection("default") # Use the name you have defined for Redis in settings.CACHES |
| 610 |
connection_pool = r.connection_pool |
| 611 |
print("Created connections so far: %d" % connection_pool._created_connections) |
| 612 |
|
| 613 |
Since the default connection pool passes all keyword arguments it doesn't use |
| 614 |
to its connections, you can also customize the connections that the pool makes |
| 615 |
by adding those options to ``CONNECTION_POOL_KWARGS``: |
| 616 |
|
| 617 |
.. code-block:: python |
| 618 |
|
| 619 |
CACHES = { |
| 620 |
"default": { |
| 621 |
# ... |
| 622 |
"OPTIONS": { |
| 623 |
"CONNECTION_POOL_KWARGS": {"max_connections": 100, "retry_on_timeout": True} |
| 624 |
} |
| 625 |
} |
| 626 |
} |
| 627 |
|
| 628 |
Use your own connection pool subclass |
| 629 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 630 |
|
| 631 |
Sometimes you want to use your own subclass of the connection pool. This is |
| 632 |
possible with django-redis using the ``CONNECTION_POOL_CLASS`` parameter in the |
| 633 |
backend options. |
| 634 |
|
| 635 |
.. code-block:: python |
| 636 |
|
| 637 |
from redis.connection import ConnectionPool |
| 638 |
|
| 639 |
class MyOwnPool(ConnectionPool): |
| 640 |
# Just doing nothing, only for example purpose |
| 641 |
pass |
| 642 |
|
| 643 |
.. code-block:: python |
| 644 |
|
| 645 |
# Omitting all backend declaration boilerplate code. |
| 646 |
|
| 647 |
"OPTIONS": { |
| 648 |
"CONNECTION_POOL_CLASS": "myproj.mypool.MyOwnPool", |
| 649 |
} |
| 650 |
|
| 651 |
Customize connection factory |
| 652 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 653 |
|
| 654 |
If none of the previous methods satisfies you, you can get in the middle of the |
| 655 |
django-redis connection factory process and customize or completely rewrite it. |
| 656 |
|
| 657 |
By default, django-redis creates connections through the |
| 658 |
``django_redis.pool.ConnectionFactory`` class that is specified in the global |
| 659 |
Django setting ``DJANGO_REDIS_CONNECTION_FACTORY``. |
| 660 |
|
| 661 |
.. code-block:: python |
| 662 |
|
| 663 |
class ConnectionFactory(object): |
| 664 |
def get_connection_pool(self, params: dict): |
| 665 |
# Given connection parameters in the `params` argument, return new |
| 666 |
# connection pool. It should be overwritten if you want do |
| 667 |
# something before/after creating the connection pool, or return |
| 668 |
# your own connection pool. |
| 669 |
pass |
| 670 |
|
| 671 |
def get_connection(self, params: dict): |
| 672 |
# Given connection parameters in the `params` argument, return a |
| 673 |
# new connection. It should be overwritten if you want to do |
| 674 |
# something before/after creating a new connection. The default |
| 675 |
# implementation uses `get_connection_pool` to obtain a pool and |
| 676 |
# create a new connection in the newly obtained pool. |
| 677 |
pass |
| 678 |
|
| 679 |
def get_or_create_connection_pool(self, params: dict): |
| 680 |
# This is a high layer on top of `get_connection_pool` for |
| 681 |
# implementing a cache of created connection pools. It should be |
| 682 |
# overwritten if you want change the default behavior. |
| 683 |
pass |
| 684 |
|
| 685 |
def make_connection_params(self, url: str) -> dict: |
| 686 |
# The responsibility of this method is to convert basic connection |
| 687 |
# parameters and other settings to fully connection pool ready |
| 688 |
# connection parameters. |
| 689 |
pass |
| 690 |
|
| 691 |
def connect(self, url: str): |
| 692 |
# This is really a public API and entry point for this factory |
| 693 |
# class. This encapsulates the main logic of creating the |
| 694 |
# previously mentioned `params` using `make_connection_params` and |
| 695 |
# creating a new connection using the `get_connection` method. |
| 696 |
pass |
| 697 |
|
| 698 |
Use the sentinel connection factory |
| 699 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 700 |
|
| 701 |
In order to facilitate using `Redis Sentinels`_, django-redis comes with a |
| 702 |
built in sentinel connection factory, which creates sentinel connection pools. |
| 703 |
In order to enable this functionality you should add the following: |
| 704 |
|
| 705 |
|
| 706 |
.. code-block:: python |
| 707 |
|
| 708 |
# Enable the alternate connection factory. |
| 709 |
DJANGO_REDIS_CONNECTION_FACTORY = 'django_redis.pool.SentinelConnectionFactory' |
| 710 |
|
| 711 |
# These sentinels are shared between all the examples, and are passed |
| 712 |
# directly to redis Sentinel. These can also be defined inline. |
| 713 |
SENTINELS = [ |
| 714 |
('sentinel-1', 26379), |
| 715 |
('sentinel-2', 26379), |
| 716 |
('sentinel-3', 26379), |
| 717 |
] |
| 718 |
|
| 719 |
CACHES = { |
| 720 |
"default": { |
| 721 |
"BACKEND": "django_redis.cache.RedisCache", |
| 722 |
# The hostname in LOCATION is the primary (service / master) name |
| 723 |
"LOCATION": "redis://service_name/db", |
| 724 |
"OPTIONS": { |
| 725 |
# While the default client will work, this will check you |
| 726 |
# have configured things correctly, and also create a |
| 727 |
# primary and replica pool for the service specified by |
| 728 |
# LOCATION rather than requiring two URLs. |
| 729 |
"CLIENT_CLASS": "django_redis.client.SentinelClient", |
| 730 |
|
| 731 |
# Sentinels which are passed directly to redis Sentinel. |
| 732 |
"SENTINELS": SENTINELS, |
| 733 |
|
| 734 |
# kwargs for redis Sentinel (optional). |
| 735 |
"SENTINEL_KWARGS": {}, |
| 736 |
|
| 737 |
# You can still override the connection pool (optional). |
| 738 |
"CONNECTION_POOL_CLASS": "redis.sentinel.SentinelConnectionPool", |
| 739 |
}, |
| 740 |
}, |
| 741 |
|
| 742 |
# A minimal example using the SentinelClient. |
| 743 |
"minimal": { |
| 744 |
"BACKEND": "django_redis.cache.RedisCache", |
| 745 |
|
| 746 |
# The SentinelClient will use this location for both the primaries |
| 747 |
# and replicas. |
| 748 |
"LOCATION": "redis://minimal_service_name/db", |
| 749 |
|
| 750 |
"OPTIONS": { |
| 751 |
"CLIENT_CLASS": "django_redis.client.SentinelClient", |
| 752 |
"SENTINELS": SENTINELS, |
| 753 |
}, |
| 754 |
}, |
| 755 |
|
| 756 |
# A minimal example using the DefaultClient. |
| 757 |
"other": { |
| 758 |
"BACKEND": "django_redis.cache.RedisCache", |
| 759 |
"LOCATION": [ |
| 760 |
# The DefaultClient is [primary, replicas...], but with the |
| 761 |
# SentinelConnectionPool it only requires one "is_master=0". |
| 762 |
"redis://other_service_name/db?is_master=1", |
| 763 |
"redis://other_service_name/db?is_master=0", |
| 764 |
], |
| 765 |
"OPTIONS": {"SENTINELS": SENTINELS}, |
| 766 |
}, |
| 767 |
|
| 768 |
# A minimal example only using only replicas in read only mode (and |
| 769 |
# the DefaultClient). |
| 770 |
"readonly": { |
| 771 |
"BACKEND": "django_redis.cache.RedisCache", |
| 772 |
"LOCATION": "redis://readonly_service_name/db?is_master=0", |
| 773 |
"OPTIONS": {"SENTINELS": SENTINELS}, |
| 774 |
}, |
| 775 |
} |
| 776 |
|
| 777 |
It is also possible to set some caches as sentinels and some as not: |
| 778 |
|
| 779 |
.. code-block:: python |
| 780 |
|
| 781 |
SENTINELS = [ |
| 782 |
('sentinel-1', 26379), |
| 783 |
('sentinel-2', 26379), |
| 784 |
('sentinel-3', 26379), |
| 785 |
] |
| 786 |
CACHES = { |
| 787 |
"sentinel": { |
| 788 |
"BACKEND": "django_redis.cache.RedisCache", |
| 789 |
"LOCATION": "redis://service_name/db", |
| 790 |
"OPTIONS": { |
| 791 |
"CLIENT_CLASS": "django_redis.client.SentinelClient", |
| 792 |
"SENTINELS": SENTINELS, |
| 793 |
"CONNECTION_POOL_CLASS": "redis.sentinel.SentinelConnectionPool", |
| 794 |
"CONNECTION_FACTORY": "django_redis.pool.SentinelConnectionFactory", |
| 795 |
}, |
| 796 |
}, |
| 797 |
"default": { |
| 798 |
"BACKEND": "django_redis.cache.RedisCache", |
| 799 |
"LOCATION": "redis://127.0.0.1:6379/1", |
| 800 |
"OPTIONS": { |
| 801 |
"CLIENT_CLASS": "django_redis.client.DefaultClient", |
| 802 |
}, |
| 803 |
}, |
| 804 |
} |
| 805 |
|
| 806 |
.. _Redis Sentinels: https://redis.io/topics/sentinel |
| 807 |
|
| 808 |
Pluggable parsers |
| 809 |
~~~~~~~~~~~~~~~~~ |
| 810 |
|
| 811 |
redis-py (the Python Redis client used by django-redis) comes with a pure |
| 812 |
Python Redis parser that works very well for most common task, but if you want |
| 813 |
some performance boost, you can use hiredis. |
| 814 |
|
| 815 |
hiredis is a Redis client written in C and it has its own parser that can be |
| 816 |
used with django-redis. |
| 817 |
|
| 818 |
.. code-block:: python |
| 819 |
|
| 820 |
"OPTIONS": { |
| 821 |
"PARSER_CLASS": "redis.connection.HiredisParser", |
| 822 |
} |
| 823 |
|
| 824 |
Note: if using version 5 of redis-py, use ``"redis.connection._HiredisParser"`` for the ``PARSER_CLASS`` due to an internal rename of classes within that package. |
| 825 |
|
| 826 |
Pluggable clients |
| 827 |
~~~~~~~~~~~~~~~~~ |
| 828 |
|
| 829 |
django-redis is designed for to be very flexible and very configurable. For it, |
| 830 |
it exposes a pluggable backends that make easy extend the default behavior, and |
| 831 |
it comes with few ones out the box. |
| 832 |
|
| 833 |
Default client |
| 834 |
^^^^^^^^^^^^^^ |
| 835 |
|
| 836 |
Almost all about the default client is explained, with one exception: the |
| 837 |
default client comes with replication support. |
| 838 |
|
| 839 |
To connect to a Redis replication setup, you should change the ``LOCATION`` to |
| 840 |
something like: |
| 841 |
|
| 842 |
.. code-block:: python |
| 843 |
|
| 844 |
"LOCATION": [ |
| 845 |
"redis://127.0.0.1:6379/1", |
| 846 |
"redis://127.0.0.1:6378/1", |
| 847 |
] |
| 848 |
|
| 849 |
The first connection string represents the primary server and the rest to |
| 850 |
replica servers. |
| 851 |
|
| 852 |
WARNING: Replication setup is not heavily tested in production environments. |
| 853 |
|
| 854 |
Shard client |
| 855 |
^^^^^^^^^^^^ |
| 856 |
|
| 857 |
This pluggable client implements client-side sharding. It inherits almost all |
| 858 |
functionality from the default client. To use it, change your cache settings to |
| 859 |
something like this: |
| 860 |
|
| 861 |
.. code-block:: python |
| 862 |
|
| 863 |
CACHES = { |
| 864 |
"default": { |
| 865 |
"BACKEND": "django_redis.cache.RedisCache", |
| 866 |
"LOCATION": [ |
| 867 |
"redis://127.0.0.1:6379/1", |
| 868 |
"redis://127.0.0.1:6379/2", |
| 869 |
], |
| 870 |
"OPTIONS": { |
| 871 |
"CLIENT_CLASS": "django_redis.client.ShardClient", |
| 872 |
} |
| 873 |
} |
| 874 |
} |
| 875 |
|
| 876 |
WARNING: Shard client is still experimental, so be careful when using it in |
| 877 |
production environments. |
| 878 |
|
| 879 |
Herd client |
| 880 |
^^^^^^^^^^^ |
| 881 |
|
| 882 |
This pluggable client helps dealing with the thundering herd problem. You can read more about it |
| 883 |
on link: `Wikipedia <https://en.wikipedia.org/wiki/Thundering_herd_problem>`_ |
| 884 |
|
| 885 |
Like previous pluggable clients, it inherits all functionality from the default client, adding some |
| 886 |
additional methods for getting/setting keys. |
| 887 |
|
| 888 |
.. code-block:: python |
| 889 |
|
| 890 |
CACHES = { |
| 891 |
"default": { |
| 892 |
"BACKEND": "django_redis.cache.RedisCache", |
| 893 |
"LOCATION": "redis://127.0.0.1:6379/1", |
| 894 |
"OPTIONS": { |
| 895 |
"CLIENT_CLASS": "django_redis.client.HerdClient", |
| 896 |
} |
| 897 |
} |
| 898 |
} |
| 899 |
|
| 900 |
This client exposes additional settings: |
| 901 |
|
| 902 |
- ``CACHE_HERD_TIMEOUT``: Set default herd timeout. (Default value: 60s) |
| 903 |
|
| 904 |
Pluggable serializer |
| 905 |
~~~~~~~~~~~~~~~~~~~~ |
| 906 |
|
| 907 |
The pluggable clients serialize data before sending it to the server. By |
| 908 |
default, django-redis serializes the data using the Python ``pickle`` module. |
| 909 |
This is very flexible and can handle a large range of object types. |
| 910 |
|
| 911 |
To serialize using JSON instead, the serializer ``JSONSerializer`` is also |
| 912 |
available. |
| 913 |
|
| 914 |
.. code-block:: python |
| 915 |
|
| 916 |
CACHES = { |
| 917 |
"default": { |
| 918 |
"BACKEND": "django_redis.cache.RedisCache", |
| 919 |
"LOCATION": "redis://127.0.0.1:6379/1", |
| 920 |
"OPTIONS": { |
| 921 |
"CLIENT_CLASS": "django_redis.client.DefaultClient", |
| 922 |
"SERIALIZER": "django_redis.serializers.json.JSONSerializer", |
| 923 |
} |
| 924 |
} |
| 925 |
} |
| 926 |
|
| 927 |
There's also support for serialization using `MsgPack`_ (that requires the |
| 928 |
msgpack library): |
| 929 |
|
| 930 |
.. code-block:: python |
| 931 |
|
| 932 |
CACHES = { |
| 933 |
"default": { |
| 934 |
"BACKEND": "django_redis.cache.RedisCache", |
| 935 |
"LOCATION": "redis://127.0.0.1:6379/1", |
| 936 |
"OPTIONS": { |
| 937 |
"CLIENT_CLASS": "django_redis.client.DefaultClient", |
| 938 |
"SERIALIZER": "django_redis.serializers.msgpack.MSGPackSerializer", |
| 939 |
} |
| 940 |
} |
| 941 |
} |
| 942 |
|
| 943 |
.. _MsgPack: https://msgpack.org/ |
| 944 |
|
| 945 |
Pluggable Redis client |
| 946 |
~~~~~~~~~~~~~~~~~~~~~~ |
| 947 |
|
| 948 |
django-redis uses the Redis client ``redis.client.StrictClient`` by default. It |
| 949 |
is possible to use an alternative client. |
| 950 |
|
| 951 |
You can customize the client used by setting ``REDIS_CLIENT_CLASS`` in the |
| 952 |
``CACHES`` setting. Optionally, you can provide arguments to this class by |
| 953 |
setting ``REDIS_CLIENT_KWARGS``. |
| 954 |
|
| 955 |
.. code-block:: python |
| 956 |
|
| 957 |
CACHES = { |
| 958 |
"default": { |
| 959 |
"OPTIONS": { |
| 960 |
"REDIS_CLIENT_CLASS": "my.module.ClientClass", |
| 961 |
"REDIS_CLIENT_KWARGS": {"some_setting": True}, |
| 962 |
} |
| 963 |
} |
| 964 |
} |
| 965 |
|
| 966 |
|
| 967 |
Closing Connections |
| 968 |
~~~~~~~~~~~~~~~~~~~ |
| 969 |
|
| 970 |
The default django-redis behavior on close() is to keep the connections to Redis server. |
| 971 |
|
| 972 |
You can change this default behaviour for all caches by the ``DJANGO_REDIS_CLOSE_CONNECTION = True`` |
| 973 |
in the django settings (globally) or (at cache level) by setting ``CLOSE_CONNECTION: True`` in the ``OPTIONS`` |
| 974 |
for each configured cache. |
| 975 |
|
| 976 |
Setting True as a value will instruct the django-redis to close all the connections (since v. 4.12.2), irrespectively of its current usage. |
| 977 |
|
| 978 |
.. code-block:: python |
| 979 |
|
| 980 |
CACHES = { |
| 981 |
"default": { |
| 982 |
"BACKEND": "django_redis.cache.RedisCache", |
| 983 |
"LOCATION": "redis://127.0.0.1:6379/1", |
| 984 |
"OPTIONS": { |
| 985 |
"CLIENT_CLASS": "django_redis.client.DefaultClient", |
| 986 |
"CLOSE_CONNECTION": True, |
| 987 |
} |
| 988 |
} |
| 989 |
} |
| 990 |
|
| 991 |
SSL/TLS and Self-Signed certificates |
| 992 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 993 |
|
| 994 |
In case you encounter a Redis server offering a TLS connection using a |
| 995 |
self-signed certificate you may disable certification verification with the |
| 996 |
following: |
| 997 |
|
| 998 |
.. code-block:: python |
| 999 |
|
| 1000 |
CACHES = { |
| 1001 |
"default": { |
| 1002 |
"BACKEND": "django_redis.cache.RedisCache", |
| 1003 |
"LOCATION": "rediss://127.0.0.1:6379/1", |
| 1004 |
"OPTIONS": { |
| 1005 |
"CLIENT_CLASS": "django_redis.client.DefaultClient", |
| 1006 |
"CONNECTION_POOL_KWARGS": {"ssl_cert_reqs": None} |
| 1007 |
} |
| 1008 |
} |
| 1009 |
} |
| 1010 |
|
| 1011 |
|
| 1012 |
License |
| 1013 |
------- |
| 1014 |
|
| 1015 |
.. code-block:: text |
| 1016 |
|
| 1017 |
Copyright (c) 2011-2015 Andrey Antukh <[email protected]> |
| 1018 |
Copyright (c) 2011 Sean Bleier |
| 1019 |
|
| 1020 |
All rights reserved. |
| 1021 |
|
| 1022 |
Redistribution and use in source and binary forms, with or without |
| 1023 |
modification, are permitted provided that the following conditions |
| 1024 |
are met: |
| 1025 |
1. Redistributions of source code must retain the above copyright |
| 1026 |
notice, this list of conditions and the following disclaimer. |
| 1027 |
2. Redistributions in binary form must reproduce the above copyright |
| 1028 |
notice, this list of conditions and the following disclaimer in the |
| 1029 |
documentation and/or other materials provided with the distribution. |
| 1030 |
3. The name of the author may not be used to endorse or promote products |
| 1031 |
derived from this software without specific prior written permission. |
| 1032 |
|
| 1033 |
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS`` AND ANY EXPRESS OR |
| 1034 |
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES |
| 1035 |
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
| 1036 |
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, |
| 1037 |
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT |
| 1038 |
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 1039 |
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 1040 |
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 1041 |
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF |
| 1042 |
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |