django - 在AppConfig的ready()方法中注册Django系统检查

标签 django

在 Django 的文档中 System check framework它说:

Checks should be registered in a file that’s loaded when your application is loaded; for example, in the AppConfig.ready() method.

该页面上或 AppConfig.ready() 方法周围的所有示例都没有显示如何执行此操作。给定一个检查方法,例如:

from django.core.checks import register, Tags

@register(Tags.compatibility)
def my_check(app_configs, **kwargs):
    # ... perform compatibility checks and collect errors
    return errors

您将如何在 AppConfig.ready() 方法中执行此操作?一个是从另一个调用的吗?上面的方法应该放到哪个文件里呢?您是否将 @register(...) 添加到 ready() 方法中?

最佳答案

来自阅读the examples on this page关于应用程序注册表和系统检查框架,似乎有(至少)两种方法来添加您自己的系统检查。要调整该页面的示例(假设您正在创建一个名为 myapp 的应用):

<小时/>

1) 创建一个 myapp/checks.py 文件,如下所示:

from django.apps import apps as camelot_apps
from django.core.checks import register, Warning
from django.core.checks import Tags as DjangoTags

class Tags(DjangoTags):
    """Do this if none of the existing tags work for you:
    https://docs.djangoproject.com/en/1.8/ref/checks/#builtin-tags
    """
    my_new_tag = 'my_new_tag'

@register(Tags.my_new_tag)
def check_taggit_is_installed(app_configs=None, **kwargs):
    "Check that django-taggit is installed when usying myapp."
    errors = []
    try:
        from taggit import models
    except ImportError:
        errors.append(
            Warning(
                "The django-taggit app is required to use myapp.",
                hint=("Install django-taggit"),
                # A unique ID so it's easier to find this warning:
                id='myapp.W001',
            )
        )
    return errors

然后在 myapp/__init__.py 中(如果不存在则创建它):

from . import checks

运行此命令应运行上面的检查:

$ ./manage.py check myapp
<小时/>

2)或者,正如我在最初的问题中所想的那样,您可以在 AppConfig 中注册该检查。因此,将上述代码保留在 myapp/check.py 中,但删除 @register(Tags.my_new_tag) 行。

然后创建包含以下内容的myapp/apps.py:

from django.core.checks import register
from .checks import Tags, check_taggit_is_installed

class MyappConfig(AppConfig):
    name = 'myapp'

    def ready(self):
        super(MyappConfig, self).ready()
        register(Tags.my_new_tag)(check_taggit_is_installed)

并更改myapps/__init__.py,使其包含以下内容:

from . import checks
default_app_config = 'myapp.apps.MyappConfig'
<小时/>

第一个示例似乎更简单,不需要自定义 AppConfig。

关于django - 在AppConfig的ready()方法中注册Django系统检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31619635/

相关文章:

python - django 1.8 SESSION_EXPIRE_AT_BROWSER_CLOSE 不工作

django - 在 Django 中使用 limit_choices_to 中的字段值

python - 防止 MySQL-Python 在数据库名称参数周围插入引号

javascript - Django channel - 回声示例不起作用

python - 创建 Django JSONField 值的副本

django - update_or_create 与 ManyToManyField

Django 表单中的 CSS 样式

django - 是否可以更改 django_auth 中的哈希算法?

python - Django 要求我安装 pytz,现在我的模型无法验证 Django

python - Django REST框架: Manager isn't available; User has been swapped for 'api.User'