+ thread-safe cache for GlobalSettings

This commit is contained in:
Phil Zhitnikov 2023-07-07 02:28:46 +04:00
parent d7ddd9ed4b
commit 5bfae66ad5

View File

@ -1,10 +1,8 @@
import time
from decimal import Decimal from decimal import Decimal
from datetime import datetime
import random import random
import string import string
import uuid
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
@ -23,7 +21,7 @@ from store.utils import create_preview, concat_not_null_values
class GlobalSettings(models.Model): class GlobalSettings(models.Model):
cached = None 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)
@ -40,18 +38,18 @@ 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.cached = self GlobalSettings.context.cached = 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 cls.cached is not None: if hasattr(cls.context, 'cached'):
return cls.cached return cls.context.cached
obj, _ = cls.objects.get_or_create(id=1) obj, _ = cls.objects.get_or_create(id=1)
cls.cached = obj cls.context.cached = obj
return obj return obj