Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redefinition of AppConfig.ready()

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?

like image 873
Michael Avatar asked May 25 '16 15:05

Michael


1 Answers

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
like image 173
Vitor Freitas Avatar answered Sep 26 '22 16:09

Vitor Freitas