django - 我对 app.py 中使用的就绪函数感到困惑

标签 django

我正在使用 django 框架工作做一些项目我是初学者,刚刚使用过 django signals 但我很困惑为什么我们需要在 ready 函数中的 app.py 中导入信号文件

下面的代码使问题更清楚,我被困在这个问题上,所以需要帮助

信号.py

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile

@receiver(post_save,sender=User)
def create_profile(sender,instance,created,**kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save,sender=User)
def save_profile(sender,instance,**kwargs):
    instance.profile.save()

应用.py

from django.apps import AppConfig

class UsersConfig(AppConfig):
    name = 'users'

    def ready(self):
        import users.signals
        #i have no idea what this function does

这里的ready函数有什么用,为什么要在这里导入信号???

如果我在顶部导入信号而不使用就绪函数怎么办?

最佳答案

what is the need of ready function here and why is it importing signals here?

ready() method [Django-doc]在注册表完全加载后调用。因此,您可以在服务器开始处理请求之前执行一些您想要执行的操作。这是在文档中指定的:

Subclasses can override this method to perform initialization tasks such as registering signals. It is called as soon as the registry is fully populated.

这里导入信号的原因是如果你不显式导入信号,Django 将不会导入信号。如果未导入 signals 模块,则信号不会在相应的模型上注册,因此如果您更改 User 模型,信号将不会被触发。

通常一个人加一个#noqa注释导入行,以防止像 pylint 这样的 linter 工具针对您不使用的导入发出警告。

from django.apps import AppConfig

class UsersConfig(AppConfig):
    name = 'users'

    def ready(self):
        import users.signals  <b># noqa</b>

关于django - 我对 app.py 中使用的就绪函数感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58362534/

相关文章:

python - 使用字段排序 mptt 树

python - str 没有在 django 中添加对象

python - celery 心跳不工作

python - 带模拟的 Django 单元测试

python - 两个Django项目共享数据库报 "table "auth_permission"already exists"错误如何解决

python - Django/SQLite 用户模型 UNIQUE 约束失败

Django celery ubuntu 14.04

python - 将 Django 与 App Engine 和 Eclipse 一起使用

django - 无法在 OS X Mavericks 上启动 Celery

python - 返回为 JSON 字符串数组而不是键值数组