Redefinition of AppConfig.ready()

故事扮演 提交于 2019-12-07 09:33:51

问题


Django 1.9.

Trying to learn signals. In the documentation for AppConfig.ready() it is said that "Subclasses can override this method to perform initialization tasks such as registering signals." (https://docs.djangoproject.com/en/1.9/ref/applications/#django.apps.AppConfig.ready).

some_app/apps.py

class SomeAppConfig(AppConfig):
    name = 'some_app'

    def ready(self):
        print("Redefined ready method in some_app")

demo_signals/settings.py

INSTALLED_APPS = [
    ...
    "some_app.apps.SomeAppConfig",
]

python manage.py runserver
Redefined ready method in some_app
Redefined ready method in some_app
Performing system checks...

System check identified no issues (0 silenced).
May 25, 2016 - 15:15:58
Django version 1.9.6, using settings 'demo_signals.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Please, note that "Redefined ready method in some_app" is printed twice.

Could you help me understand why it is called twice. And this is not my mistake, why two calls are necessary for registering signals?


回答1:


When you use python manage.py runserver Django start two processes, one for the actual development server and other to reload your application when the code change

You can test it importing os inside your AppConfig class and print the process id inside the ready function like so:

import os

class SomeAppConfig(AppConfig):
    name = 'some_app'

    def ready(self):
        print(os.getpid())

You will see it prints two different processes

You can also start the server without the reload option, and you will see only one process running (and your code print("Redefined ready method in some_app") will only be executed once):

python manage.py runserver --noreload


来源:https://stackoverflow.com/questions/37441564/redefinition-of-appconfig-ready

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!