From 1dbcf9a005842c3fdd97537f1bd4fab5b96b972f Mon Sep 17 00:00:00 2001 From: Adam Johnson Date: Tue, 27 Jun 2023 08:11:09 +0100 Subject: [PATCH] Fixed #34681 -- Optimized memcache_key_warnings(). --- django/core/cache/backends/base.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/django/core/cache/backends/base.py b/django/core/cache/backends/base.py index eb4b3eac6d..09b0a5f9c8 100644 --- a/django/core/cache/backends/base.py +++ b/django/core/cache/backends/base.py @@ -6,6 +6,7 @@ from asgiref.sync import sync_to_async from django.core.exceptions import ImproperlyConfigured from django.utils.module_loading import import_string +from django.utils.regex_helper import _lazy_re_compile class InvalidCacheBackendError(ImproperlyConfigured): @@ -388,16 +389,17 @@ class BaseCache: pass +memcached_error_chars_re = _lazy_re_compile(r"[\x00-\x20\x7f]") + + def memcache_key_warnings(key): if len(key) > MEMCACHE_MAX_KEY_LENGTH: yield ( "Cache key will cause errors if used with memcached: %r " "(longer than %s)" % (key, MEMCACHE_MAX_KEY_LENGTH) ) - for char in key: - if ord(char) < 33 or ord(char) == 127: - yield ( - "Cache key contains characters that will cause errors if " - "used with memcached: %r" % key - ) - break + if memcached_error_chars_re.search(key): + yield ( + "Cache key contains characters that will cause errors if used with " + f"memcached: {key!r}" + )