Commit 90ce5d46 authored by Przemysław Suliga's avatar Przemysław Suliga Committed by Tim Graham
Browse files

Fixed #26462 -- Fixed Python 2 UnicodeEncodeError when warning about long cache keys.

parent 369fa471
Loading
Loading
Loading
Loading
+1 −1
Original line number Diff line number Diff line
@@ -235,7 +235,7 @@ class BaseCache(object):
        """
        if len(key) > MEMCACHE_MAX_KEY_LENGTH:
            warnings.warn('Cache key will cause errors if used with memcached: '
                    '%s (longer than %s)' % (key, MEMCACHE_MAX_KEY_LENGTH),
                    '%r (longer than %s)' % (key, MEMCACHE_MAX_KEY_LENGTH),
                    CacheKeyWarning)
        for char in key:
            if ord(char) < 33 or ord(char) == 127:
+18 −2
Original line number Diff line number Diff line
@@ -585,15 +585,31 @@ class BaseCacheTests(object):
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter("always")
                # memcached does not allow whitespace or control characters in keys
                cache.set('key with spaces', 'value')
                key = 'key with spaces and 清'
                cache.set(key, 'value')
                self.assertEqual(len(w), 1)
                self.assertIsInstance(w[0].message, CacheKeyWarning)
                self.assertEqual(
                    # warnings.warn() crashes on Python 2 if message isn't
                    # coercible to str.
                    str(w[0].message.args[0]),
                    "Cache key contains characters that will cause errors if used "
                    "with memcached: %r" % key,
                )
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter("always")
                # memcached limits key length to 250
                cache.set('a' * 251, 'value')
                key = ('a' * 250) + ''
                cache.set(key, 'value')
                self.assertEqual(len(w), 1)
                self.assertIsInstance(w[0].message, CacheKeyWarning)
                self.assertEqual(
                    # warnings.warn() crashes on Python 2 if message isn't
                    # coercible to str.
                    str(w[0].message.args[0]),
                    'Cache key will cause errors if used with memcached: '
                    '%r (longer than %s)' % (key, 250),
                )
        finally:
            cache.key_func = old_func