diff --git a/store/models.py b/store/models.py index 8b0e985..d1aaa8e 100644 --- a/store/models.py +++ b/store/models.py @@ -2,7 +2,7 @@ from decimal import Decimal import random import string from io import BytesIO -from threading import local as LocalContext + from django.conf import settings from django.contrib.admin import display @@ -18,11 +18,10 @@ from django.utils.translation import gettext_lazy as _ from django_cleanup import cleanup from store.utils import create_preview, concat_not_null_values +from utils.cache import InMemoryCache class GlobalSettings(models.Model): - context = LocalContext() - # currency yuan_rate = models.DecimalField('Курс CNY/RUB', max_digits=10, decimal_places=2, default=0) # Chinadelivery @@ -38,18 +37,20 @@ class GlobalSettings(models.Model): # Store only one instance of GlobalSettings self.__class__.objects.exclude(id=self.id).delete() super().save(*args, **kwargs) - GlobalSettings.context.cached = self + + InMemoryCache.set('GlobalSettings', self) def __str__(self) -> str: return f'GlobalSettings for {self.id}' @classmethod def load(cls) -> 'GlobalSettings': - if hasattr(cls.context, 'cached'): - return cls.context.cached + cached = InMemoryCache.get('GlobalSettings') + if cached: + return cached obj, _ = cls.objects.get_or_create(id=1) - cls.context.cached = obj + InMemoryCache.set('GlobalSettings', obj) return obj diff --git a/utils/cache.py b/utils/cache.py new file mode 100644 index 0000000..0831e4a --- /dev/null +++ b/utils/cache.py @@ -0,0 +1,13 @@ +import threading + +thread_local = threading.local() + + +class InMemoryCache: + @classmethod + def get(cls, key: str): + return getattr(thread_local, key, None) + + @classmethod + def set(cls, key: str, value): + setattr(thread_local, key, value)