在Django中,如何防止AppConfig.ready()中的信号导入多次运行?

时间:2016-07-17 11:00:36

标签: python django signals django-signals

保持信号组织:

__init__.py

default_app_config = 'posts.apps.PostsConfig'

apps.py

from django.apps import AppConfig


class PostsConfig(AppConfig):
    name = 'posts'

    def ready(self):
        import posts.signals

如何确保ready()import posts.signals仅运行一次?

1 个答案:

答案 0 :(得分:0)

from django.apps import AppConfig


class PostsConfig(AppConfig):
    name = 'posts'
    ready_has_run = False

    def ready(self):
        if self.ready_has_run:
            return
        import posts.signals
        self.ready_has_run = True