+ InMemoryCache for GlobalSettings

This commit is contained in:
Phil Zhitnikov 2023-07-07 02:48:30 +04:00
parent 5bfae66ad5
commit ddceee5d7e
2 changed files with 21 additions and 7 deletions

View File

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

13
utils/cache.py Normal file
View File

@ -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)