我有一个只需要实例化一次的对象。尝试使用 redis 缓存实例失败,错误为 cache.set("some_key", singles, timeout=60*60*24*30)
但由于其他线程操作而出现序列化错误:
TypeError: can't pickle _thread.lock objects
但是,我可以根据需要轻松缓存其他实例。
因此,我正在寻找一种创建单例对象的方法,我也尝试过:
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()
但我注意到我得到Found: 0 singles
在 2-3 个请求之后。请问在不使用可能尝试序列化和持久化对象的第三方库的情况下在 Djnago 上创建单例的最佳方法是什么(这在我的情况下是不可能的)
最佳答案
这是我的单例抽象模型。
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()
关于python - 如何在 Django 中实现单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49735906/