Django检查框架函数在哪里?

xmq68pz9  于 2023-04-22  发布在  Go
关注(0)|答案(1)|浏览(99)

django框架允许你编写自己的检查https://docs.djangoproject.com/en/4.2/topics/checks/,但它没有说明代码应该放在哪里,以及如何将其挂钩到检查框架中。

gk7wooem

gk7wooem1#

#1它应该住在哪里?

这完全取决于你!我通常在{root}/common,特别是{root}/common/internal中放置这样的即兴作品。我不确定这是否是一个好的做法,但它对我很有效!

#2如何勾入check框架

不是100%确定你的意思,但你所要做的就是导入一个{root}/{app}/apps.py文件中的文件,当你运行任何服务器命令时,你的检查都会运行;像python manage.py runserver
下面是我测试的一个示例检查,它检查settings.py中的TESTING var是否是有效的Boolean。

common/internal/checks.py
from django.conf import settings
from django.core.checks import Error, Tags, Warning, register

E001 = Error(
    "'%s' is an Invalid Setting for TESTING. Must be a Bool" % settings.TESTING,
    id='settings_testing.E001',
)

@register(Tags.compatibility)
def check_testing(app_configs, **kwargs):
    if not isinstance(settings.TESTING, bool):
        return [E001]
    return []
app1/apps.py
from django.apps import AppConfig

from common.internal.checks import check_testing

class App1Config(AppConfig):
    name = 'app1'
失败输出示例
  • djrun-〉python manage.py runserver,不错的别名!推荐
λ djrun
Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.10/threading.py", line 953, in run
    self._target(*self._args, **self._kwargs)
  File "[REDACTED]", line 64, in wrapper
    fn(*args, **kwargs)
  File "[REDACTED]", line 118, in inner_run
    self.check(display_num_errors=True)
  File "[REDACTED]", line 469, in check
    raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:

ERRORS:
?: (caches.E001) 'blah' is an Invalid Setting for TESTING. Must be a Bool

System check identified 1 issue (0 silenced).

相关问题