Giter Site home page Giter Site logo

django-redis's Introduction

Redis cache backend for Django

Jazzband GitHub Actions Coverage https://img.shields.io/pypi/v/django-redis.svg?style=flat

This is a Jazzband project. By contributing you agree to abide by the Contributor Code of Conduct and follow the guidelines.

Introduction

django-redis is a BSD licensed, full featured Redis cache and session backend for Django.

Why use django-redis?

  • Uses native redis-py url notation connection strings
  • Pluggable clients
  • Pluggable parsers
  • Pluggable serializers
  • Primary/secondary support in the default client
  • Comprehensive test suite
  • Used in production in several projects as cache and session storage
  • Supports infinite timeouts
  • Facilities for raw access to Redis client/connection pool
  • Highly configurable (can emulate memcached exception behavior, for example)
  • Unix sockets supported by default

Requirements

User guide

Installation

Install with pip:

$ python -m pip install django-redis

Configure as cache backend

To start using django-redis, you should change your Django cache settings to something like:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

django-redis uses the redis-py native URL notation for connection strings, it allows better interoperability and has a connection string in more "standard" way. Some examples:

  • redis://[[username]:[password]]@localhost:6379/0
  • rediss://[[username]:[password]]@localhost:6379/0
  • unix://[[username]:[password]]@/path/to/socket.sock?db=0

Three URL schemes are supported:

  • redis://: creates a normal TCP socket connection
  • rediss://: creates a SSL wrapped TCP socket connection
  • unix:// creates a Unix Domain Socket connection

There are several ways to specify a database number:

  • A db querystring option, e.g. redis://localhost?db=0
  • If using the redis:// scheme, the path argument of the URL, e.g. redis://localhost/0

When using Redis' ACLs, you will need to add the username to the URL (and provide the password with the Cache OPTIONS). The login for the user django would look like this:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://django@localhost:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "PASSWORD": "mysecret"
        }
    }
}

An alternative would be write both username and password into the URL:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://django:mysecret@localhost:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

In some circumstances the password you should use to connect Redis is not URL-safe, in this case you can escape it or just use the convenience option in OPTIONS dict:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "PASSWORD": "mysecret"
        }
    }
}

Take care, that this option does not overwrites the password in the uri, so if you have set the password in the uri, this settings will be ignored.

Configure as session backend

Django can by default use any cache backend as session backend and you benefit from that by using django-redis as backend for session storage without installing any additional backends:

SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"

Testing with django-redis

django-redis supports customizing the underlying Redis client (see "Pluggable clients"). This can be used for testing purposes.

In case you want to flush all data from the cache after a test, add the following lines to your test class:

from django_redis import get_redis_connection

def tearDown(self):
    get_redis_connection("default").flushall()

Advanced usage

Pickle version

For almost all values, django-redis uses pickle to serialize objects.

The pickle.DEFAULT_PROTOCOL version of pickle is used by default to ensure safe upgrades and compatibility across Python versions. If you want set a concrete version, you can do it, using PICKLE_VERSION option:

CACHES = {
    "default": {
        # ...
        "OPTIONS": {
            "PICKLE_VERSION": -1  # Will use highest protocol version available
        }
    }
}

Socket timeout

Socket timeout can be set using SOCKET_TIMEOUT and SOCKET_CONNECT_TIMEOUT options:

CACHES = {
    "default": {
        # ...
        "OPTIONS": {
            "SOCKET_CONNECT_TIMEOUT": 5,  # seconds
            "SOCKET_TIMEOUT": 5,  # seconds
        }
    }
}

SOCKET_CONNECT_TIMEOUT is the timeout for the connection to be established and SOCKET_TIMEOUT is the timeout for read and write operations after the connection is established.

Compression support

django-redis comes with compression support out of the box, but is deactivated by default. You can activate it setting up a concrete backend:

CACHES = {
    "default": {
        # ...
        "OPTIONS": {
            "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor",
        }
    }
}

Let see an example, of how make it work with lzma compression format:

import lzma

CACHES = {
    "default": {
        # ...
        "OPTIONS": {
            "COMPRESSOR": "django_redis.compressors.lzma.LzmaCompressor",
        }
    }
}

Lz4 compression support (requires the lz4 library):

import lz4

CACHES = {
    "default": {
        # ...
        "OPTIONS": {
            "COMPRESSOR": "django_redis.compressors.lz4.Lz4Compressor",
        }
    }
}

Zstandard (zstd) compression support (requires the pyzstd library):

import pyzstd

CACHES = {
    "default": {
        # ...
        "OPTIONS": {
            "COMPRESSOR": "django_redis.compressors.zstd.ZStdCompressor",
        }
    }
}

Gzip compression support:

import gzip

CACHES = {
    "default": {
        # ...
        "OPTIONS": {
            "COMPRESSOR": "django_redis.compressors.gzip.GzipCompressor",
        }
    }
}

Memcached exceptions behavior

In some situations, when Redis is only used for cache, you do not want exceptions when Redis is down. This is default behavior in the memcached backend and it can be emulated in django-redis.

For setup memcached like behaviour (ignore connection exceptions), you should set IGNORE_EXCEPTIONS settings on your cache configuration:

CACHES = {
    "default": {
        # ...
        "OPTIONS": {
            "IGNORE_EXCEPTIONS": True,
        }
    }
}

Also, you can apply the same settings to all configured caches, you can set the global flag in your settings:

DJANGO_REDIS_IGNORE_EXCEPTIONS = True

Log Ignored Exceptions

When ignoring exceptions with IGNORE_EXCEPTIONS or DJANGO_REDIS_IGNORE_EXCEPTIONS, you may optionally log exceptions using the global variable DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS in your settings file:

DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS = True

If you wish to specify the logger in which the exceptions are output, simply set the global variable DJANGO_REDIS_LOGGER to the string name and/or path of the desired logger. This will default to __name__ if no logger is specified and DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS is True:

DJANGO_REDIS_LOGGER = 'some.specified.logger'

Infinite timeout

django-redis comes with infinite timeouts support out of the box. And it behaves in same way as django backend contract specifies:

  • timeout=0 expires the value immediately.
  • timeout=None infinite timeout
cache.set("key", "value", timeout=None)

Get ttl (time-to-live) from key

With Redis, you can access to ttl of any stored key, for it, django-redis exposes ttl function.

It returns:

  • 0 if key does not exists (or already expired).
  • None for keys that exists but does not have any expiration.
  • ttl value for any volatile key (any key that has expiration).
>>> from django.core.cache import cache
>>> cache.set("foo", "value", timeout=25)
>>> cache.ttl("foo")
25
>>> cache.ttl("not-existent")
0

With Redis, you can access to ttl of any stored key in milliseconds, for it, django-redis exposes pttl function.

>>> from django.core.cache import cache
>>> cache.set("foo", "value", timeout=25)
>>> cache.pttl("foo")
25000
>>> cache.pttl("not-existent")
0

Expire & Persist

Additionally to the simple ttl query, you can send persist a concrete key or specify a new expiration timeout using the persist and expire methods:

>>> cache.set("foo", "bar", timeout=22)
>>> cache.ttl("foo")
22
>>> cache.persist("foo")
True
>>> cache.ttl("foo")
None
>>> cache.set("foo", "bar", timeout=22)
>>> cache.expire("foo", timeout=5)
True
>>> cache.ttl("foo")
5

The expire_at method can be used to make the key expire at a specific moment in time.

>>> cache.set("foo", "bar", timeout=22)
>>> cache.expire_at("foo", datetime.now() + timedelta(hours=1))
True
>>> cache.ttl("foo")
3600

The pexpire_at method can be used to make the key expire at a specific moment in time with milliseconds precision:

>>> cache.set("foo", "bar", timeout=22)
>>> cache.pexpire_at("foo", datetime.now() + timedelta(milliseconds=900, hours=1))
True
>>> cache.ttl("foo")
3601
>>> cache.pttl("foo")
3600900

The pexpire method can be used to provide millisecond precision:

>>> cache.set("foo", "bar", timeout=22)
>>> cache.pexpire("foo", timeout=5500)
True
>>> cache.pttl("foo")
5500

Locks

It also supports the Redis ability to create Redis distributed named locks. The Lock interface is identical to the threading.Lock so you can use it as replacement.

with cache.lock("somekey"):
    do_some_thing()

Scan & Delete keys in bulk

django-redis comes with some additional methods that help with searching or deleting keys using glob patterns.

>>> from django.core.cache import cache
>>> cache.keys("foo_*")
["foo_1", "foo_2"]

A simple search like this will return all matched values. In databases with a large number of keys this isn't suitable method. Instead, you can use the iter_keys function that works like the keys function but uses Redis server side cursors. Calling iter_keys will return a generator that you can then iterate over efficiently.

>>> from django.core.cache import cache
>>> cache.iter_keys("foo_*")
<generator object algo at 0x7ffa9c2713a8>
>>> next(cache.iter_keys("foo_*"))
"foo_1"

For deleting keys, you should use delete_pattern which has the same glob pattern syntax as the keys function and returns the number of deleted keys.

>>> from django.core.cache import cache
>>> cache.delete_pattern("foo_*")

To achieve the best performance while deleting many keys, you should set DJANGO_REDIS_SCAN_ITERSIZE to a relatively high number (e.g., 100_000) by default in Django settings or pass it directly to the delete_pattern.

>>> from django.core.cache import cache
>>> cache.delete_pattern("foo_*", itersize=100_000)

Redis native commands

django-redis has limited support for some Redis atomic operations, such as the commands SETNX and INCR.

You can use the SETNX command through the backend set() method with the nx parameter:

>>> from django.core.cache import cache
>>> cache.set("key", "value1", nx=True)
True
>>> cache.set("key", "value2", nx=True)
False
>>> cache.get("key")
"value1"

Also, the incr and decr methods use Redis atomic operations when the value that a key contains is suitable for it.

Raw client access

In some situations your application requires access to a raw Redis client to use some advanced features that aren't exposed by the Django cache interface. To avoid storing another setting for creating a raw connection, django-redis exposes functions with which you can obtain a raw client reusing the cache connection string: get_redis_connection(alias).

>>> from django_redis import get_redis_connection
>>> con = get_redis_connection("default")
>>> con
<redis.client.Redis object at 0x2dc4510>

WARNING: Not all pluggable clients support this feature.

Connection pools

Behind the scenes, django-redis uses the underlying redis-py connection pool implementation, and exposes a simple way to configure it. Alternatively, you can directly customize a connection/connection pool creation for a backend.

The default redis-py behavior is to not close connections, recycling them when possible.

Configure default connection pool

The default connection pool is simple. For example, you can customize the maximum number of connections in the pool by setting CONNECTION_POOL_KWARGS in the CACHES setting:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        # ...
        "OPTIONS": {
            "CONNECTION_POOL_KWARGS": {"max_connections": 100}
        }
    }
}

You can verify how many connections the pool has opened with the following snippet:

from django_redis import get_redis_connection

r = get_redis_connection("default")  # Use the name you have defined for Redis in settings.CACHES
connection_pool = r.connection_pool
print("Created connections so far: %d" % connection_pool._created_connections)

Since the default connection pool passes all keyword arguments it doesn't use to its connections, you can also customize the connections that the pool makes by adding those options to CONNECTION_POOL_KWARGS:

CACHES = {
    "default": {
        # ...
        "OPTIONS": {
            "CONNECTION_POOL_KWARGS": {"max_connections": 100, "retry_on_timeout": True}
        }
    }
}

Use your own connection pool subclass

Sometimes you want to use your own subclass of the connection pool. This is possible with django-redis using the CONNECTION_POOL_CLASS parameter in the backend options.

from redis.connection import ConnectionPool

class MyOwnPool(ConnectionPool):
    # Just doing nothing, only for example purpose
    pass
# Omitting all backend declaration boilerplate code.

"OPTIONS": {
    "CONNECTION_POOL_CLASS": "myproj.mypool.MyOwnPool",
}

Customize connection factory

If none of the previous methods satisfies you, you can get in the middle of the django-redis connection factory process and customize or completely rewrite it.

By default, django-redis creates connections through the django_redis.pool.ConnectionFactory class that is specified in the global Django setting DJANGO_REDIS_CONNECTION_FACTORY.

class ConnectionFactory(object):
    def get_connection_pool(self, params: dict):
        # Given connection parameters in the `params` argument, return new
        # connection pool. It should be overwritten if you want do
        # something before/after creating the connection pool, or return
        # your own connection pool.
        pass

    def get_connection(self, params: dict):
        # Given connection parameters in the `params` argument, return a
        # new connection. It should be overwritten if you want to do
        # something before/after creating a new connection. The default
        # implementation uses `get_connection_pool` to obtain a pool and
        # create a new connection in the newly obtained pool.
        pass

    def get_or_create_connection_pool(self, params: dict):
        # This is a high layer on top of `get_connection_pool` for
        # implementing a cache of created connection pools. It should be
        # overwritten if you want change the default behavior.
        pass

    def make_connection_params(self, url: str) -> dict:
        # The responsibility of this method is to convert basic connection
        # parameters and other settings to fully connection pool ready
        # connection parameters.
        pass

    def connect(self, url: str):
        # This is really a public API and entry point for this factory
        # class. This encapsulates the main logic of creating the
        # previously mentioned `params` using `make_connection_params` and
        # creating a new connection using the `get_connection` method.
        pass

Use the sentinel connection factory

In order to facilitate using Redis Sentinels, django-redis comes with a built in sentinel connection factory, which creates sentinel connection pools. In order to enable this functionality you should add the following:

# Enable the alternate connection factory.
DJANGO_REDIS_CONNECTION_FACTORY = 'django_redis.pool.SentinelConnectionFactory'

# These sentinels are shared between all the examples, and are passed
# directly to redis Sentinel. These can also be defined inline.
SENTINELS = [
    ('sentinel-1', 26379),
    ('sentinel-2', 26379),
    ('sentinel-3', 26379),
]

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        # The hostname in LOCATION is the primary (service / master) name
        "LOCATION": "redis://service_name/db",
        "OPTIONS": {
            # While the default client will work, this will check you
            # have configured things correctly, and also create a
            # primary and replica pool for the service specified by
            # LOCATION rather than requiring two URLs.
            "CLIENT_CLASS": "django_redis.client.SentinelClient",

            # Sentinels which are passed directly to redis Sentinel.
            "SENTINELS": SENTINELS,

            # kwargs for redis Sentinel (optional).
            "SENTINEL_KWARGS": {},

            # You can still override the connection pool (optional).
            "CONNECTION_POOL_CLASS": "redis.sentinel.SentinelConnectionPool",
        },
    },

    # A minimal example using the SentinelClient.
    "minimal": {
        "BACKEND": "django_redis.cache.RedisCache",

        # The SentinelClient will use this location for both the primaries
        # and replicas.
        "LOCATION": "redis://minimal_service_name/db",

        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.SentinelClient",
            "SENTINELS": SENTINELS,
        },
    },

    # A minimal example using the DefaultClient.
    "other": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": [
            # The DefaultClient is [primary, replicas...], but with the
            # SentinelConnectionPool it only requires one "is_master=0".
            "redis://other_service_name/db?is_master=1",
            "redis://other_service_name/db?is_master=0",
        ],
        "OPTIONS": {"SENTINELS": SENTINELS},
    },

    # A minimal example only using only replicas in read only mode (and
    # the DefaultClient).
    "readonly": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://readonly_service_name/db?is_master=0",
        "OPTIONS": {"SENTINELS": SENTINELS},
    },
}

It is also possible to set some caches as sentinels and some as not:

SENTINELS = [
    ('sentinel-1', 26379),
    ('sentinel-2', 26379),
    ('sentinel-3', 26379),
]
CACHES = {
    "sentinel": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://service_name/db",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.SentinelClient",
            "SENTINELS": SENTINELS,
            "CONNECTION_POOL_CLASS": "redis.sentinel.SentinelConnectionPool",
            "CONNECTION_FACTORY": "django_redis.pool.SentinelConnectionFactory",
        },
    },
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        },
    },
}

Pluggable parsers

redis-py (the Python Redis client used by django-redis) comes with a pure Python Redis parser that works very well for most common task, but if you want some performance boost, you can use hiredis.

hiredis is a Redis client written in C and it has its own parser that can be used with django-redis.

"OPTIONS": {
    "PARSER_CLASS": "redis.connection.HiredisParser",
}

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.

Pluggable clients

django-redis is designed for to be very flexible and very configurable. For it, it exposes a pluggable backends that make easy extend the default behavior, and it comes with few ones out the box.

Default client

Almost all about the default client is explained, with one exception: the default client comes with replication support.

To connect to a Redis replication setup, you should change the LOCATION to something like:

"LOCATION": [
    "redis://127.0.0.1:6379/1",
    "redis://127.0.0.1:6378/1",
]

The first connection string represents the primary server and the rest to replica servers.

WARNING: Replication setup is not heavily tested in production environments.

Shard client

This pluggable client implements client-side sharding. It inherits almost all functionality from the default client. To use it, change your cache settings to something like this:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": [
            "redis://127.0.0.1:6379/1",
            "redis://127.0.0.1:6379/2",
        ],
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.ShardClient",
        }
    }
}

WARNING: Shard client is still experimental, so be careful when using it in production environments.

Herd client

This pluggable client helps dealing with the thundering herd problem. You can read more about it on link: Wikipedia

Like previous pluggable clients, it inherits all functionality from the default client, adding some additional methods for getting/setting keys.

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.HerdClient",
        }
    }
}

This client exposes additional settings:

  • CACHE_HERD_TIMEOUT: Set default herd timeout. (Default value: 60s)

Pluggable serializer

The pluggable clients serialize data before sending it to the server. By default, django-redis serializes the data using the Python pickle module. This is very flexible and can handle a large range of object types.

To serialize using JSON instead, the serializer JSONSerializer is also available.

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "SERIALIZER": "django_redis.serializers.json.JSONSerializer",
        }
    }
}

There's also support for serialization using MsgPack (that requires the msgpack library):

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "SERIALIZER": "django_redis.serializers.msgpack.MSGPackSerializer",
        }
    }
}

Pluggable Redis client

django-redis uses the Redis client redis.client.StrictClient by default. It is possible to use an alternative client.

You can customize the client used by setting REDIS_CLIENT_CLASS in the CACHES setting. Optionally, you can provide arguments to this class by setting REDIS_CLIENT_KWARGS.

CACHES = {
    "default": {
        "OPTIONS": {
            "REDIS_CLIENT_CLASS": "my.module.ClientClass",
            "REDIS_CLIENT_KWARGS": {"some_setting": True},
        }
    }
}

Closing Connections

The default django-redis behavior on close() is to keep the connections to Redis server.

You can change this default behaviour for all caches by the DJANGO_REDIS_CLOSE_CONNECTION = True in the django settings (globally) or (at cache level) by setting CLOSE_CONNECTION: True in the OPTIONS for each configured cache.

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.

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CLOSE_CONNECTION": True,
        }
    }
}

SSL/TLS and Self-Signed certificates

In case you encounter a Redis server offering a TLS connection using a self-signed certificate you may disable certification verification with the following:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "rediss://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"ssl_cert_reqs": None}
        }
    }
}

License

Copyright (c) 2011-2015 Andrey Antukh <[email protected]>
Copyright (c) 2011 Sean Bleier

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS`` AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

django-redis's People

Contributors

alanjds avatar aleszoulek avatar barttc avatar bertrandbordage avatar dependabot[bot] avatar foarsitter avatar honzakral avatar iurisilvio avatar jacklinke avatar jdufresne avatar jezdez avatar kysre avatar linux-warrior avatar mattdennewitz avatar michael-k avatar myungsegyo avatar niwinz avatar peymanslh avatar pinoatrome avatar pre-commit-ci[bot] avatar rootart avatar sarathak avatar sebleier avatar teferi avatar terencehonles avatar theoldmop avatar tmarice avatar twidi avatar wisdompill avatar yoavweiss avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-redis's Issues

ShardClient broken in Django 1.4.2

Hi,

I'm testing the 3.x branch in Django 1.4.2 and the sharded client does not work, getting this exception upon connection close:

  File "/Users/uroy1/.virtualenvs/calltime-api/lib/python2.6/site-packages/redis_cache/cache.py", line 144, in close
    self.client.close(**kwargs)
TypeError: close() got an unexpected keyword argument 'signal'

Having a look to the code, it seems that the close method in the ShardClient class should have this signature at least (and actually should be doing something with the connections if it's configured to be closing them):

    def close(self, **kwargs):
        pass

Best regards,
Urtzi.

timeout=None in django 1.6

Just noticed and by looking at the master, django-redis does not fully support django 1.6 . Previously, passing None explicitly would use the default timeout value. Now it will cache the value forever. This change was made in order to allow timeout = 0 to let the cache expire immediately. I'll most likely make a fork, cause I need this badly.

point of this fork

Original django-redis-cache seems to be alive now. But the main point of this fork from README file is to revive the project. What else?

Django tests expect negative timeouts to remove keys from cache.

I couldn't find any info in official django docs on how cached backends should treat negative or zero values, but according to
django/contrib/sessions/tests.py โ€” SessionTestsMixin.test_actual_expiry

django now does expect negative values to remove items from cache. At least starting with 1.6.x/stable branch.

django-redis currently just sets the item without timeout if timeout is less than or equal to zero. I propose supporting negative timeouts (since redis's EXPIRE does support them.) SETEX doesn't seem to support them, but that can be solved with pipelining. (I also intend on asking @antirez if that's a bug or a by-design decision)

I'll attach a pull-request shortly

redis < 2.9 warning

We just upgraded to 3.6 from 3.3 and now we have a new warning every time we use django-redis. This would be fine, if it made sense.

/home/<>/.virtualenvs/<>/local/lib/python2.7/site-packages/redis_cache/client/__init__.py:19: RuntimeWarning: sentinel client is unsuported with redis-py<2.9
  RuntimeWarning)

We have redis 2.9.1 installed, which can be verified by running pip freeze | grep "redis==2" which gives:

redis==2.9.1

Having the warning in the __init__ file also means that the notice is visible whenever the module is imported, which is pretty much whenever anything else involving django-redis is used... even if the sentinel client isn't.

Add hiredis to install requirements

I'm a first time redis user. I don't realize that example configuration in README file uses hiredis as parser class. I was unaware that hiredis parser class is not included in redis package. Maybe hiredis should be added to install requirements, or at least mentioned in README to prevent confusion for first time user.

package naming is confusing

pypi name is django-redis
python package is redis_cache

there is another pypi package called django-redis-cache

IndexError: list index out of range

Hi,

Getting this error from time to time when using django-redis:

redis_cache.hash_ring in get_node_pos
IndexError: list index out of range

Context:
'_hash': 'fff669c4a9b088e574b496b38144e59563d99ee1ab9c6e5d4952072757a77158'
'idx': 128

Possible fix (file: hash_ring.py, line 49):

Instead of:

idx = min(idx, (self.replicas * len(self.nodes))-1)

Use this (because the list is 0 indexed):

idx = min(idx, (self.replicas * len(self.nodes))) - 1

Not sure if this causes any other issues.

INC and DEC operations are not atomim

I write a test like:

'''python

def test_incr(self):
    def inc(cache):
        for i in range(100000):                                                                                                  
            cache.incr("num")                                                                                                                                                                                                                                                

    self.cache.set("num", 0)                                                                                                     
    threads = [Thread(target=inc, args=(self.cache,)) for i in range(10)]                                                                                                                                                                                   

    for t in threads:                                                                                                            
        t.start()                                                                                                                                                                                                                                                                  

    for t in threads:                                                                                                            
        t.join()                                                                                                                                                                                                                                                              

    self.assertEqual(self.cache.get("num"), 1000000, "%d != 1000000" % (self.cache.get("num")))

'''

Having a result like:

FAIL: test_incr (redis_backend_testapp_inc.tests.DjangoRedisCacheTests)

Traceback (most recent call last):
File "/home/lasi/devel/django-redis/tests/redis_backend_testapp_inc/tests.py", line 36, in test_incr
self.assertEqual(self.cache.get("num"), 1000000, "%d != 1000000" % (self.cache.get("num")))
AssertionError: 233816 != 1000000

Connection pool class in settings

When using multiple threads or greenlets, default ConnectionPool may be overlimited. redis.connection.BlockingConnectionPool easily solves this problem, but it can't be used without tricky monkey-patching.

Better if ConnectionPool class and its arguments would be specified in settings.

stats app import error

With latest code, I am getting ImportError for stats app.
It seems you removed the ConnectionPoolHandler from utils, but still that is imported and used in stats/views.

Here is the traceback -
Traceback:
File "/home/vagrant/project/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response

  1.                 response = middleware_method(request)
    
    File "/home/vagrant/project/venv/local/lib/python2.7/site-packages/django/utils/importlib.py" in import_module
  2. **import**(name)
    
    File "/vagrant/src/redant/urls.py" in
  3. url(r'^redis/status/', include('redis_cache.stats.urls', namespace='redis_cache')),
    
    File "/home/vagrant/project/venv/local/lib/python2.7/site-packages/django/conf/urls/init.py" in include
  4.     urlconf_module = import_module(urlconf_module)
    
    File "/home/vagrant/project/venv/local/lib/python2.7/site-packages/django/utils/importlib.py" in import_module
  5. **import**(name)
    
    File "/home/vagrant/project/venv/local/lib/python2.7/site-packages/redis_cache/stats/urls.py" in
  6. from .views import RedisStatsView
    File "/home/vagrant/project/venv/local/lib/python2.7/site-packages/redis_cache/stats/views.py" in
  7. from ..util import ConnectionPoolHandler

Exception Type: ImportError at /
Exception Value: cannot import name ConnectionPoolHandler

Default settings leaking TCP/IP connections?

Maybe the default Redis connection pool settings should be lowered a bit. I was one who did it and now I am running some problems with them :P

I am running an UWSGI web server with the following settings. It is almost no traffic Django site, default Ubuntu 12.04 installation. It has < 100 requests per day.

processes = 4
threads = 2

I checked with PS and there are actually 4 UWSGI processes.

Somehow Redis connections keep piling up, clogging the server:

   redis-ser 31546      redis  994u     IPv4             332011      0t0        TCP localhost:6379->localhost:47332 (ESTABLISHED)

And then:

   lsof|grep -i redis|wc -l
  1020 <--- open Redis TCP/IP connections

As far as I calculate max open connections should be number of processes * number of max connections per pool?

Apparently something is not closing connections or UWSGI is somehow misusing the pool.

Or am I missing something?

Why pickle strings?

Hello @niwibe ,

IMHO, I found strange django-redis behavior in simple JSON caching.

from django.core.cache import cache
cache.set("123", '{"test":"test"}')

Redis monitor:

~$ redis-cli monitor
OK
1394490905.897550 [1 127.0.0.1:49782] "SETEX" "123" "300" "\x80\x02U\x0f{\"test\":\"test\"}q\x01."

Why does it pickle simple JSON string? Pickled version will take more memory.
Please explain - is it desired behavior?

Support DJANGO_REDIS_IGNORE_EXCEPTIONS per client

My application uses couple of Redis instances for different purposes.
I would like to omit exceptions for only one of them.
For now DJANGO_REDIS_IGNORE_EXCEPTIONS is global setting.

Something like this

CACHES = {
    'default': {
        "BACKEND": "redis_cache.cache.RedisCache",
        "LOCATION": config['redis_url_first'],
        "OPTIONS": {
            "CLIENT_CLASS": "redis_cache.client.DefaultClient",
            "DJANGO_REDIS_IGNORE_EXCEPTIONS": True
        }
    },
    `other`: {
        "BACKEND": "redis_cache.cache.RedisCache",
        "LOCATION": config['redis_url_second'],
        "OPTIONS": {
            "CLIENT_CLASS": "redis_cache.client.DefaultClient",
            "DJANGO_REDIS_IGNORE_EXCEPTIONS": False
        }
    }  
}

Client does not handle Django 1.6 DEFAULT_TIMEOUT correctly.

django.core.cache.backends.base.DEFAULT_TIMEOUT is by default a blank object in Django 1.6. Apps that explicitly set this value as the timeout will fail due to proper int checks not being in place.

The line client.expire(key, int(timeout)) within DefaultClient.set causes a TypeError while trying to convert object() to int.

The Django base cache implementation catches this exception and deals with it accordingly. The DefaultClient redis implementation checks for timeout > 0, which returns True for the default object but then fails while trying to cast it.

Failure to work with unixsocket

When trying to work with unixsocket, I got an error from python-redis indicating "Error 22 connecting to unix socket: . Invalid argument.".
I further debugged it and saw that the "path" parameter that should contain the socket is empty.

I found the blame to be in util.py:73 (in ConnectionPoolHandler.connection_pool).
Instead of:
kwargs['path'] = kwargs['unix_socket_path']
it should be:
params['path'] = kwargs['unix_socket_path']

Fixing it on my local machine fixed that error.
I'll also send a corresponding pull request.

3.0 Release Discussion

This is for a 3.0 release. All code should be on the devel branch.

Bakward incompatible changes

  • Unified connection string

New features

  • Modular clients separated from backend class.
  • Can set ignore exceptions (like memcached backend default behavior)
  • Python3 Support.

Differentiating between django-redis and django-redis-cache at import-time

I'm writing a patch to https://github.com/ui/django-rq to allow it to tailgate its configuration on the django-redis cache setup. I want this patch to be compatible with both django-redis and django-redis-cache, but the method of getting the Redis connection differs between the two. For testing purposes, I want to test the two packages separately, but the fact that they both import as redis_cache makes this a bit difficult. I'm basing my import-time detection of which package is installed on the existence of get_redis_connection in the redis_cache module, but I wanted to check if this is the best way to do this check.

Unable to load redis_cache

I tried using django-redis but it trows this error in production only, probably the combination of software versions is causing this:

Traceback (most recent call last):
File "manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/srv/coclea_virt_env/lib/python2.6/site-packages/Django-1.4.2-py2.6.egg/django/core/management/init.py", line 443, in execute_from_command_line
utility.execute()
File "/srv/coclea_virt_env/lib/python2.6/site-packages/Django-1.4.2-py2.6.egg/django/core/management/init.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/srv/coclea_virt_env/lib/python2.6/site-packages/Django-1.4.2-py2.6.egg/django/core/management/base.py", line 196, in run_from_argv
self.execute(_args, *_options.dict)
File "/srv/coclea_virt_env/lib/python2.6/site-packages/Django-1.4.2-py2.6.egg/django/core/management/base.py", line 217, in execute
translation.activate('en-us')
File "/srv/coclea_virt_env/lib/python2.6/site-packages/Django-1.4.2-py2.6.egg/django/utils/translation/init.py", line 105, in activate
return _trans.activate(language)
File "/srv/coclea_virt_env/lib/python2.6/site-packages/Django-1.4.2-py2.6.egg/django/utils/translation/trans_real.py", line 194, in activate
_active.value = translation(language)
File "/srv/coclea_virt_env/lib/python2.6/site-packages/Django-1.4.2-py2.6.egg/django/utils/translation/trans_real.py", line 183, in translation
default_translation = _fetch(settings.LANGUAGE_CODE)
File "/srv/coclea_virt_env/lib/python2.6/site-packages/Django-1.4.2-py2.6.egg/django/utils/translation/trans_real.py", line 160, in _fetch
app = import_module(appname)
File "/srv/coclea_virt_env/lib/python2.6/site-packages/Django-1.4.2-py2.6.egg/django/utils/importlib.py", line 35, in import_module
import(name)
File "/srv/coclea_virt_env/lib/python2.6/site-packages/django_redis-3.1.2-py2.6.egg/redis_cache/init.py", line 3, in
from django.core.cache import get_cache
File "/srv/coclea_virt_env/lib/python2.6/site-packages/Django-1.4.2-py2.6.egg/django/core/cache/init.py", line 187, in
cache = get_cache(DEFAULT_CACHE_ALIAS)
File "/srv/coclea_virt_env/lib/python2.6/site-packages/Django-1.4.2-py2.6.egg/django/core/cache/init.py", line 178, in get_cache
"Could not find backend '%s': %s" % (backend, e))
django.core.cache.backends.base.InvalidCacheBackendError: Could not find backend 'redis_cache.cache.RedisCache': 'tuple' object has no attribute 'major'

Software Debian 6.0 (Squeeze):

  • Python 2.6.6
  • redis-py 2.7.1
  • django_redis 3.1.2
  • django 1.4.2
  • redis 2.4.11

Breaks Django Contrib Session Tests (CacheSessionTests, CacheDBSessionTests, etc....)

I have followed instructions and installed django-redis and set up the cache using the redis_cache backend--confirmed that it is working, etc... but it is breaking the session tests for cache backends. It appears that sessions are not expiring appropriately in the test_actual_expiry test. Using Django 1.5.4:

FAIL: test_actual_expiry (django.contrib.sessions.tests.CacheDBSessionTests)

Traceback (most recent call last):
File "env/lib/python2.7/site-packages/django/contrib/sessions/tests.py", line 291, in test_actual_expiry
self.assertNotIn('foo', new_session)
AssertionError: 'foo' unexpectedly found in <django.contrib.sessions.backends.cached_db.SessionStore object at 0x10b919e90>

FAIL: test_actual_expiry (django.contrib.sessions.tests.CacheDBSessionWithTimeZoneTests)

Traceback (most recent call last):
File "env/lib/python2.7/site-packages/django/contrib/sessions/tests.py", line 291, in test_actual_expiry
self.assertNotIn('foo', new_session)
AssertionError: 'foo' unexpectedly found in <django.contrib.sessions.backends.cached_db.SessionStore object at 0x10b92edd0>

FAIL: test_actual_expiry (django.contrib.sessions.tests.CacheSessionTests)

Traceback (most recent call last):
File "env/lib/python2.7/site-packages/django/contrib/sessions/tests.py", line 291, in test_actual_expiry
self.assertNotIn('foo', new_session)
AssertionError: 'foo' unexpectedly found in <django.contrib.sessions.backends.cache.SessionStore object at 0x10b931750>

Fake client for tests

It would be great to implement fake client for testing purposes, which supports majority of API calls.
We may use django.core.cache.backends.locmem.LocMemCache as a basis.

Default build-docs behavior dangerous

If you run build-docs.sh against a clean checkout, asciidoc not installed, the script will clear all files in your repository, leaving only static folder and do a commit on the top of this. You may lose your unfinished edits.

Maybe check that you do not have any unfinished changes doing rm -rf *.

Float value in SOCKET_TIMEOUT option

The documentation says:

You can optionally set a timeout for redis operations by specifying an integer or float value for SOCKET_TIMEOUT in your CACHES entry

But in the file "pool.py":

 kwargs['socket_timeout'] = int(self.options['SOCKET_TIMEOUT'])

It's impossible to set a timeout value less than one second. Is there reason for it?

Failover support

I've noticed to differences with official memcached backends:

  • In case of failure this backend throws an exception while memcached backend silently ignores it
  • In case of failure that instance is disabled for 30 seconds and other one is used until that instance is back (that is implemented internally by memcached library and not by the django memcached backend)

I find both features very useful and would like to know if you have plans to integrate them or if you are interested in contributions around this feature

How do I do an atomic incr() if the key is not set?

If I perform an incr(key) where the key is not already set, the incr() should set the key to 1. However, the default behavior in Django's get_cache function does not allow you to do this. Is there a way to drop down to the redis-py client that allows you to do this atomic incr?

Use other Backend if Redis isn't available

Hello everyone,

I'm start to using django-redis but when the Redis Server is down the websites crash's..

http://i.imgur.com/hw1DT.png

I believe that a better approach could be if the Redis Server is off then you can specify others backend, like callbacks, even if it's dummy backend.. just to do not break all the site, even because the data properly are in your DB like MySQL and so on.. if you access to MySQL why break all the web site?

Some ways, for example:

You specify inside django-redis an second backend, just the name, that find for settings.CACHES and one function.

For example, if django-redis try to connect to the Server without successfully so the other backend could be used and the function is called, this function could be used to inform for example, the admin that the Redis Server is off or even execute some command to get up Redis Server.

Cya!

Suggested MAX_ENTRIES?

Great project! It was really easy to install, and so far is great. Is there a suggested value for MAX_ENTRIES in the django cache options dictionary?

I think the default is 300, but it seems like you could reasonably make that a lot bigger with this project.

Failover to cached_db

I think it would be a good feature to implement a way to fallback to database cache instead of other Redis instance.
Is it possible to be done? I would like to add this feature if it fits the django-redis purposes.

dealing with thundering herd problem?

I have the result of a query that is very expensive. This is cached in redis for 15 minutes. Once the cache expires the queries are obviously run and the cache warmed again.

But at the point of expiration the thundering herd problem issue can happen.

http://en.wikipedia.org/wiki/Thundering_herd_problem

Currently I'm using an algorithm that continues to deliver stale cache while a thread kicks in the moment expiration happens and updates the cache.

But it would be much better if it is a built-in feature of a caching backend, and it is in some backend: https://github.com/ericflo/django-newcache

Any plan on this feature?

access to setnx

It would be nice to have access to redis setnx functionality. Either through additional method or through additional optional parameter in set method.

I'm ready to implement it either way if there is a chance for it to be merged. What do you think?

Dependencies needed to build documents

It is not documented what you need to build the docs and how. Having cleaner instructions would encourage providing patches to the documentation, as the submitter has a chance to preview the changes on their local computer.

For example you need something like asciidoc, pygment and niwi. The last is pygment theme, but I could not figure out where and how to install it and if it is needed.

Process hangs when the remote server is running but doesn't allow you to access.

I'm using redis_cache something like this

from redis_cache import get_redis_connection
from rq import Queue

try:
    queue = Queue(connection=get_redis_connection('db'))
    queue.enqueue(some_action, some_data)
except Exception:
    do_something_else(some_data)

I was expecting a ConnectionError or some other exceptions when the remote server refused me to access, but the program just didn't respond anything.

I set the timeout in the caches settings, but it also not work.

"db": {
    "BACKEND": "redis_cache.cache.RedisCache",
        "LOCATION": "127.0.0.1:6379:2",
        "TIMEOUT": 120,
        "OPTIONS": {
            "CLIENT_CLASS": "redis_cache.client.DefaultClient",
        }
    },

Could someone give a clue about this?

Is TIMEOUT setting respected by django-redis?

Hello, can anybody confirm that TIMEOUT setting is respected by django-redis? This is my configuration (I want key/values to never expire):

CACHES = {
    'default': {
        'BACKEND': 'redis_cache.cache.RedisCache',
        'LOCATION': '127.0.0.1:6379',
        'KEY_PREFIX': 'my-prefix',
        'OPTIONS': {
            'TIMEOUT': None
        }
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.