+ InMemoryCache for GlobalSettings
This commit is contained in:
parent
5bfae66ad5
commit
ddceee5d7e
|
|
@ -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
|
||||
|
||||
|
||||
|
|
|
|||
13
utils/cache.py
Normal file
13
utils/cache.py
Normal 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)
|
||||
Loading…
Reference in New Issue
Block a user