From 6d3272eed4da3e344d1fbc4e739e57f5ee7867d8 Mon Sep 17 00:00:00 2001 From: NiedielnitsevIvan <81557788+NiedielnitsevIvan@users.noreply.github.com> Date: Mon, 1 Apr 2024 13:28:47 +0300 Subject: [PATCH] refactor: refactor memcache keys getting (#2525) --- cms/djangoapps/contentstore/utils.py | 31 +++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/cms/djangoapps/contentstore/utils.py b/cms/djangoapps/contentstore/utils.py index 8579c045255b..1a69a11c2e88 100644 --- a/cms/djangoapps/contentstore/utils.py +++ b/cms/djangoapps/contentstore/utils.py @@ -8,7 +8,7 @@ from collections import defaultdict from contextlib import contextmanager from datetime import datetime, timezone -from urllib.parse import quote_plus +from urllib.parse import quote_plus, unquote from uuid import uuid4 from django.conf import settings @@ -2299,5 +2299,30 @@ def drop_course_sidebar_blocks_cache(course_id: str): Drop the course sidebar blocks cache for the given course. """ cache_key_prefix = f"course_sidebar_blocks_{course_id}" - all_cache_keys = cache.keys('*') if hasattr(cache, 'keys') else [] - cache.delete_many(filter(lambda key: key.startswith(cache_key_prefix), all_cache_keys)) + cache_keys = get_cache_keys(cache_key_prefix) + + cache.delete_many(cache_keys) + + +def get_cache_keys(cache_key_prefix): + """ + Get all cache keys for the given cache key prefix. + + LocMemCache does not have a keys method, so we need to iterate over the cache + and manually filter out the keys that match the given prefix. + """ + cache_backend = settings.CACHES['default']['BACKEND'] + if cache_backend == 'django_redis.cache.RedisCache': + yield cache.iter_keys(f"{cache_key_prefix}*") + elif cache_backend == 'django.core.cache.backends.locmem.LocMemCache': + for key in cache._cache.keys(): # pylint: disable=protected-access + try: + decoded_key = unquote(key.split(':', 2)[-1], encoding='utf-8') + except IndexError: + continue + + if decoded_key.startswith(cache_key_prefix): + yield decoded_key + else: + log.error(f"Unsupported cache backend: {cache_backend}") + yield