Commit be20ec70 authored by Carl Meyer's avatar Carl Meyer

Handle __str__/__unicode__ correctly for Python 2/3.

parent eb17f1bd
...@@ -2,7 +2,7 @@ from django.core.cache.backends.base import BaseCache, InvalidCacheBackendError ...@@ -2,7 +2,7 @@ from django.core.cache.backends.base import BaseCache, InvalidCacheBackendError
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.utils import importlib from django.utils import importlib
from django.utils.datastructures import SortedDict from django.utils.datastructures import SortedDict
from .compat import smart_text, smart_bytes from .compat import smart_text, smart_bytes, python_2_unicode_compatible
try: try:
import cPickle as pickle import cPickle as pickle
...@@ -18,6 +18,7 @@ from redis.connection import UnixDomainSocketConnection, Connection ...@@ -18,6 +18,7 @@ from redis.connection import UnixDomainSocketConnection, Connection
from redis.connection import DefaultParser from redis.connection import DefaultParser
@python_2_unicode_compatible
class CacheKey(object): class CacheKey(object):
""" """
A stub string class that we can use to check if a key was created already. A stub string class that we can use to check if a key was created already.
...@@ -29,13 +30,10 @@ class CacheKey(object): ...@@ -29,13 +30,10 @@ class CacheKey(object):
return self._key == other return self._key == other
def __str__(self): def __str__(self):
return self.__unicode__() return smart_text(self._key)
def __repr__(self): def __repr__(self):
return self.__unicode__() return repr(self._key)
def __unicode__(self):
return smart_text(self._key)
def __hash__(self): def __hash__(self):
return hash(self._key) return hash(self._key)
......
import sys
PY3 = (sys.version_info >= (3,))
try: try:
# Django 1.5+ # Django 1.5+
from django.utils.encoding import smart_text, smart_bytes from django.utils.encoding import smart_text, smart_bytes
...@@ -6,3 +10,19 @@ except ImportError: ...@@ -6,3 +10,19 @@ except ImportError:
from django.utils.encoding import smart_unicode, smart_str from django.utils.encoding import smart_unicode, smart_str
smart_text = smart_unicode smart_text = smart_unicode
smart_bytes = smart_str smart_bytes = smart_str
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
Backported from Django 1.5+.
"""
if not PY3:
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment