python - 如何在 Django 中实现单例

标签 python django singleton

我有一个只需要实例化一次的对象。尝试使用 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/

相关文章:

python - ValueError : The model is not configured to compute accuracy. 您应该传递 `metrics=["准确度“]` to the ` model.compile()` 方法

python - 如何以编程方式设置 forms.CharField 文本?

java - 如何在多个模块中的公共(public)库中使用 Singleton 而不会发生冲突?

java - 如果一个 Singleton 没有被任何其他对象引用,它如何或为什么保持 Activity 状态?

ios - 带有 AVAudioPlayer 的 iOS 中的 Swift : Singleton not working the way I hoped it would

python - 将 Tensorflow 数据集转换为 2 个包含图像和标签的数组

python - 如何更改 Pandas DataFrame 面积图上的年份间隔?

python - Django:显示管理站点的换行符?

python - 无法使用 upstart/supervisord 运行 uwsgi

Django:使用 API 和 Pickle 发布 Pandas 数据帧或如何在 Django REST Framework 中使用 "hello world"序列化器和 View 来查看二进制数据