问题
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