如何在Django中实现Singleton

时间:2018-04-09 14:54:03

标签: python django singleton

我有一个只需要实例化的对象。尝试使用redis缓存实例失败,错误$query = $db->query(" SELECT SUM(aatt.present='1') AS total_present, SUM(aatt.absent='1') AS total_absent, aatt.sid, att.att_date, att.att_month, att.att_year FROM ".TABLE_PREFIX."school_att att LEFT JOIN ".TABLE_PREFIX."school_att_attendance aatt ON (aatt.att_month=att.att_month) WHERE {$where_clause} GROUP BY att.att_date, att.att_month, att.att_year;") 但由于其他线程操作而导致序列化错误:

  

TypeError:无法pickle _thread.lock对象

但是,我可以根据需要轻松缓存其他实例。

因此,我正在寻找一种创建Singleton对象的方法,我也尝试过:

cache.set("some_key", singles, timeout=60*60*24*30)

在view.py中,我呼吁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 ,但我注意到我

  

找到:0单身

2-3次请求后。请问在没有使用可能尝试序列化和持久化对象的第三方库的情况下,在Djnago上创建Singleton的最佳方法是什么(在我的情况下这是不可能的)

1 个答案:

答案 0 :(得分:0)

这是我的Singleton抽象模型。

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()