New in Django 1.7\.html
系統檢查框架是爲了驗證Django項目的一系列靜態檢查。它能夠檢測到廣泛的問題,而且提供如何修復的提示。這個框架能夠被擴展,因此你能夠輕易地添加你本身的檢查。python
檢查能夠由check
命令顯式觸發。檢查會在大多數命令以前隱式觸發,包括runserver
和 migrate
。因爲性能因素,檢查不做爲在部署中使用的WSGI棧的一部分運行。若是你須要在你的部署服務器上運行系統檢查,顯式使用check
來觸發它們。django
嚴重的錯誤會徹底阻止Django命令(像runserver
)的運行。少數問題會經過控制檯來報告。若是你檢查了警告的緣由,而且願意無視它,你可使用你項目設置文件中的SILENCED_SYSTEM_CHECKS
設置,來隱藏特定的警告。服務器
_系統檢查參考_中列出了全部Django可執行的全部檢查。app
這個框架十分靈活,容許你編寫函數,執行任何其餘類型的所需檢查。下面是一個樁(stub)檢查函數的例子:框架
from django.core.checks import register @register() def example_check(app_configs, **kwargs): errors = [] # ... your check logic here return errors
檢查函數_必須_接受 app_configs
參數;這個參數是要被檢查的應用列表。若是是None,檢查會運行在項目中_全部_安裝的應用上。**kwargs
參數用於進一步的擴展。less
這個函數必須返回消息的列表。若是檢查的結果中沒有發現問題,檢查函數必須返回一個空列表。ide
_class _CheckMessage
(_level_, _msg_, _hint_, _obj=None_, _id=None_)函數
由檢查方法產生的警告和錯誤必須是CheckMessage
的示例。CheckMessage
的實例封裝了一個可報告的錯誤或者警告。它同時也提供了可應用到消息的上下文或者提示,以及一個用於過濾的惟一的標識符。性能
它的概念很是相似於_消息框架_或者 _日誌框架_中的消息。消息使用代表其嚴重性的level
來標記。
構造器的參數是:
level
The severity of the message. Use one of the
predefined values: DEBUG
, INFO
, WARNING
, ERROR
,CRITICAL
. If the level is greater or equal to ERROR
, then Django
will prevent management commands from executing. Messages with
level lower than ERROR
(i.e. warnings) are reported to the console,
but can be silenced.
msg
A short (less than 80 characters) string describing the problem. The string
should not contain newlines.
hint
A single-line string providing a hint for fixing the problem. If no hint
can be provided, or the hint is self-evident from the error message, the
hint can be omitted, or a value of None
can be used.
obj
Optional. An object providing context for the message (for example, the
model where the problem was discovered). The object should be a model, field,
or manager or any other object that defines __str__
method (on
Python 2 you need to define __unicode__
method). The method is used while
reporting all messages and its result precedes the message.
id
Optional string. A unique identifier for the issue. Identifiers should
follow the pattern applabel.X001
, where X
is one of the lettersCEWID
, indicating the message severity (C
for criticals,E
for errors and so). The number can be allocated by the application,
but should be unique within that application.
也有一些快捷方式,使得建立通用級別的消息變得簡單。當使用這些方法時你能夠忽略level
參數,由於它由類名稱暗示。
_class _Debug
(_msg_, _hint_, _obj=None_, _id=None_)
_class _Info
(_msg_, _hint_, _obj=None_, _id=None_)
_class _Warning
(_msg_, _hint_, _obj=None_, _id=None_)
_class _Error
(_msg_, _hint_, _obj=None_, _id=None_)
_class _Critical
(_msg_, _hint_, _obj=None_, _id=None_)
消息是可比較的。你能夠輕易地編寫測試:
from django.core.checks import Error errors = checked_object.check() expected_errors = [ Error( 'an error', hint=None, obj=checked_object, id='myapp.E001', ) ] self.assertEqual(errors, expected_errors)
最後,你的檢查函數必須使用系統檢查登記處來顯式註冊。
register
(_*tags)(function_)
你能夠向 register
傳遞任意數量的標籤來標記你的檢查。Tagging checks is useful since it allows you to run only a certain group of checks. For example, to register a compatibility check, you would make the following call:
from django.core.checks import register, Tags @register(Tags.compatibility) def my_check(app_configs, **kwargs): # ... perform compatibility checks and collect errors return errors
New in Django 1.8\.
你能夠註冊「部署的檢查」,它們只和產品配置文件相關,像這樣:
@register(Tags.security, deploy=True) def my_check(app_configs, **kwargs): ...
這些檢查只在 --deploy
選項傳遞給check
命令的狀況下運行。
你也能夠經過向register
傳遞一個可調用對象(一般是個函數)做爲第一個函數,將 register
做爲函數使用,而不是一個裝飾器。
下面的代碼和上面等價:
def my_check(app_configs, **kwargs): ... register(my_check, Tags.security, deploy=True)
Changed in Django 1.8:
添加了將註冊用做函數的功能。
在一些狀況下,你並不須要註冊檢查函數 -- 你能夠直接使用現有的註冊。
字段、方法和模型管理器都實現了check()
方法,它已經使用檢查框架註冊。若是你想要添加額外的檢查,你能夠擴展基類中的實現,進行任何你須要的額外檢查,而且將任何消息附加到基類生成的消息中。強烈推薦你將每一個檢查分配到單獨的方法中。
考慮一個例子,其中你要實現一個叫作RangedIntegerField
的自定義字段。這個字段向IntegerField
的構造器中添加min
和 max
參數。你可能想添加一個檢查,來確保用戶提供了小於等於最大值的最小值。下面的代碼段展現瞭如何實現這個檢查:
from django.core import checks from django.db import models class RangedIntegerField(models.IntegerField): def __init__(self, min=None, max=None, **kwargs): super(RangedIntegerField, self).__init__(**kwargs) self.min = min self.max = max def check(self, **kwargs): # Call the superclass errors = super(RangedIntegerField, self).check(**kwargs) # Do some custom checks and add messages to `errors`: errors.extend(self._check_min_max_values(**kwargs)) # Return all errors and warnings return errors def _check_min_max_values(self, **kwargs): if (self.min is not None and self.max is not None and self.min > self.max): return [ checks.Error( 'min greater than max.', hint='Decrease min or increase max.', obj=self, id='myapp.E001', ) ] # When no error, return an empty list return []
若是你想要向模型管理器添加檢查,應該在你的Manager
的子類上執行一樣的方法。
若是你想要向模型類添加檢查,方法也_大體_相同:惟一的不一樣是檢查是類方法,並非實例方法:
class MyModel(models.Model): @classmethod def check(cls, **kwargs): errors = super(MyModel, cls).check(**kwargs) # ... your own checks ... return errors
譯者:Django 文檔協做翻譯小組,原文:System check framework。
本文以 CC BY-NC-SA 3.0 協議發佈,轉載請保留做者署名和文章出處。
Django 文檔協做翻譯小組人手緊缺,有興趣的朋友能夠加入咱們,徹底公益性質。交流羣:467338606。