Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added enforce_encoding #602

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions django_redis/client/default.py
Original file line number Diff line number Diff line change
@@ -132,6 +132,7 @@ def set(
client: Optional[Redis] = None,
nx: bool = False,
xx: bool = False,
enforce_encoding: bool = False,
) -> bool:
"""
Persist a value to the cache, and set an optional expiration time.
@@ -140,7 +141,7 @@ def set(
setnx instead of set.
"""
nkey = self.make_key(key, version=version)
nvalue = self.encode(value)
nvalue = self.encode(value, enforce_encoding=enforce_encoding)

if timeout is DEFAULT_TIMEOUT:
timeout = self._backend.default_timeout
@@ -448,12 +449,16 @@ def decode(self, value: Union[bytes, int]) -> Any:
value = self._serializer.loads(value)
return value

def encode(self, value: Any) -> Union[bytes, Any]:
def encode(self, value: Any, enforce_encoding: bool = False) -> Union[bytes, Any]:
"""
Encode the given value.
"""

if isinstance(value, bool) or not isinstance(value, int):
if (
isinstance(value, bool)
or not isinstance(value, int)
or enforce_encoding is True
):
value = self._serializer.dumps(value)
value = self._compressor.compress(value)
return value
16 changes: 16 additions & 0 deletions tests/test_backend.py
Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@
import threading
import time
from datetime import timedelta
from enum import IntEnum
from typing import List, Union, cast
from unittest.mock import patch

@@ -19,6 +20,11 @@
herd.CACHE_HERD_TIMEOUT = 2


class Values2(IntEnum):
SOMETHING_1 = 1
SOMETHING_2 = 2


class TestDjangoRedisCache:
def test_setnx(self, cache: RedisCache):
# we should ensure there is no test_key_nx in redis
@@ -650,6 +656,16 @@ def test_expire_at(self, cache: RedisCache):
expiration_time = datetime.datetime.now() + timedelta(hours=2)
assert cache.expire_at("not-existent-key", expiration_time) is False

def test_intenum(self, cache: RedisCache):

cache.set("hello", Values2.SOMETHING_1, enforce_encoding=True)

value = cache.get("hello")

assert value == Values2.SOMETHING_1

assert isinstance(value, Values2)

def test_lock(self, cache: RedisCache):
lock = cache.lock("foobar")
lock.acquire(blocking=True)