Pau*_*llo 5 python django singleton
我有一个只需要实例化一次的对象。尝试使用 Redis 缓存实例失败并出现错误cache.set("some_key", singles, timeout=60*60*24*30),但由于其他线程操作而出现序列化错误:
类型错误:无法 pickle _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
Run Code Online (Sandbox Code Playgroud)
在 view.py 中我调用了 Singleton.loadSingles()但我注意到我得到了
已找到: 0 条单打
2-3次请求后。请问在 Djnago 上创建 Singleton 的最佳方法是什么,而不使用可能尝试序列化和持久化对象的第三方库(在我的情况下这是不可能的)
小智 5
我发现使用唯一索引来完成此任务更容易
class SingletonModel(models.Model):
_singleton = models.BooleanField(default=True, editable=False, unique=True)
class Meta:
abstract = True
Run Code Online (Sandbox Code Playgroud)
这是我的单例抽象模型。
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()
Run Code Online (Sandbox Code Playgroud)