我有一个只需要实例化一次的对象。尝试使用redis缓存实例,但由于其他线程操作,错误cache.set("some_key", singles, timeout=60*60*24*30)失败,但得到了序列化错误:
TypeError:不能对_thread.lock对象进行分类
但是,我可以根据需要轻松地缓存其他实例。
因此,我正在寻找一种创建Singleton对象的方法,我还尝试了:
class SingletonModel(models.Model):
class Meta:
abstract = True
def save(self, *args, **kwargs):
# self.pk = 1
super(SingletonModel, self).save(*args, **kwargs)
# if self.can_cache:
# self.set_cache()
def delete(self, *args, **kwargs):
pass
class Singleton(SingletonModel):
singles = []
@classmethod
def setSingles(cls, singles):
cls.singles = singles
@classmethod
def loadSingles(cls):
sins = cls.singles
log.warning("*****Found: {} singles".format(len(sins)))
if len(sins) == 0:
sins = cls.doSomeLongOperation()
cls.setSingles(sins)
return sins在view.py中,我调用了Singleton.loadSingles(),但我注意到
发现:0名单身
在2-3次请求之后。请不要使用尝试序列化和持久化对象的第三方库(在我的情况下是不可能的),在Djnago上创建Singleton的最佳方法是什么?
发布于 2021-10-31 22:08:28
我发现用一个唯一的索引来完成这个任务比较容易。
class SingletonModel(models.Model):
_singleton = models.BooleanField(default=True, editable=False, unique=True)
class Meta:
abstract = True发布于 2018-04-09 15:53:49
这是我的单身抽象模型。
class SingletonModel(models.Model):
"""Singleton Django Model"""
class Meta:
abstract = True
def save(self, *args, **kwargs):
"""
Save object to the database. Removes all other entries if there
are any.
"""
self.__class__.objects.exclude(id=self.id).delete()
super(SingletonModel, self).save(*args, **kwargs)
@classmethod
def load(cls):
"""
Load object from the database. Failing that, create a new empty
(default) instance of the object and return it (without saving it
to the database).
"""
try:
return cls.objects.get()
except cls.DoesNotExist:
return cls()发布于 2022-10-02 17:32:47
下面的代码只是防止创建一个新的实例的收入模型,如果一个存在。我认为这应该会给你指明正确的方向。
祝你好运!
class RevenueWallet(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class Meta:
verbose_name = "Revenue"
def save(self, *args, **kwargs):
"""
:param args:
:param kwargs:
:return:
"""
# Checking if pk exists so that updates can be saved
if not RevenueWallet.objects.filter(pk=self.pk).exists() and RevenueWallet.objects.exists():
raise ValidationError('There can be only one instance of this model')
return super(RevenueWallet, self).save(*args, **kwargs)https://stackoverflow.com/questions/49735906
复制相似问题