Skip to content

Commit

Permalink
Use string values for django-cache keys #230 (#242)
Browse files Browse the repository at this point in the history
* Use string values for django-chache keys.

When django cache backend tests the key provided by django_celery_results, It wants to have str type value. 
byte values result in the following exception being raised:

  File "/opt/exaboard/eXaboard/lib/python3.6/site-packages/django/core/cache/backends/base.py", line 287, in memcache_key_warnings
    if ord(char) < 33 or ord(char) == 127:
TypeError: ord() expected string of length 1, but int found

* Remove old super call argument

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Add test that saves key value in byte format

* Syntax fix for test_convert_key_from_byte_to_str

* Fixes based on flake8 failures

* Fix t/unit/backends/test_cache.py:64:50: W291 trailing whitespace

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
badeendjuh and pre-commit-ci[bot] committed Oct 11, 2021
1 parent ddfdb7a commit 3b567d5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
4 changes: 4 additions & 0 deletions django_celery_results/backends/cache.py
Expand Up @@ -3,6 +3,7 @@
from celery.backends.base import KeyValueStoreBackend
from django.core.cache import cache as default_cache
from django.core.cache import caches
from kombu.utils.encoding import bytes_to_str


class CacheBackend(KeyValueStoreBackend):
Expand All @@ -15,12 +16,15 @@ def __init__(self, *args, **kwargs):
self.serializer = 'pickle'

def get(self, key):
key = bytes_to_str(key)
return self.cache_backend.get(key)

def set(self, key, value):
key = bytes_to_str(key)
self.cache_backend.set(key, value, self.expires)

def delete(self, key):
key = bytes_to_str(key)
self.cache_backend.delete(key)

def encode(self, data):
Expand Down
13 changes: 13 additions & 0 deletions t/unit/backends/test_cache.py
Expand Up @@ -4,6 +4,7 @@
import pytest
from billiard.einfo import ExceptionInfo
from celery import result, states, uuid
from kombu.utils.encoding import bytes_to_str

from django_celery_results.backends.cache import CacheBackend

Expand Down Expand Up @@ -59,6 +60,18 @@ def test_is_pickled(self):
assert rindb.get('foo') == 'baz'
assert rindb.get('bar').data == 12345

def test_convert_key_from_byte_to_str(self):
""" Tests that key in byte form passed into cache
are succesfully completed """
tid = bytes_to_str(uuid())

assert self.b.get_status(tid) == states.PENDING
assert self.b.get_result(tid) is None

self.b.mark_as_done(tid, 42)
assert self.b.get_status(tid) == states.SUCCESS
assert self.b.get_result(tid) == 42

def test_mark_as_failure(self):
einfo = None
tid3 = uuid()
Expand Down

0 comments on commit 3b567d5

Please sign in to comment.