重新定义AppConfig.ready() [英] Redefinition of AppConfig.ready()

查看:110
本文介绍了重新定义AppConfig.ready()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django 1.9。

Django 1.9.

尝试学习信号。在AppConfig.ready()的文档中,据说子类可以重写此方法以执行初始化任务,例如注册信号。 ( https://docs.djangoproject.com/en /1.9/ref/applications/#django.apps.AppConfig.ready )。

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.

请注意, some_app中的预定义就绪方法打印两次。

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?

推荐答案

使用时python manage.py runserver Django启动两个进程,一个用于实际的开发服务器,另一个在代码更改时重新加载您的应用程序

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

AppConfig 类中导入 os 进行测试,并在 ready 中打印进程ID。 code>函数如下:

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

您也可以在没有重新加载选项的情况下启动服务器,然后只能看到一个正在运行的进程(并且您的代码 print( some_app中的预定义就绪方法)只会执行一次):

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

这篇关于重新定义AppConfig.ready()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆