# 系統檢查框架
New in Django 1.7\.
系統檢查框架是為了驗證Django項目的一系列靜態檢查。它可以檢測到普遍的問題,并且提供如何修復的提示。這個框架可以被擴展,所以你可以輕易地添加你自己的檢查。
檢查可以由[`check`](../ref/django-admin.html#django-admin-check)命令顯式觸發。檢查會在大多數命令之前隱式觸發,包括[`runserver`](../ref/django-admin.html#django-admin-runserver) 和 [`migrate`](../ref/django-admin.html#django-admin-migrate)。由于性能因素,檢查不作為在部署中使用的WSGI棧的一部分運行。如果你需要在你的部署服務器上運行系統檢查,顯式使用[`check`](../ref/django-admin.html#django-admin-check)來觸發它們。
嚴重的錯誤會完全阻止Django命令(像[`runserver`](../ref/django-admin.html#django-admin-runserver))的運行。少數問題會通過控制臺來報告。如果你檢查了警告的原因,并且愿意無視它,你可以使用你項目設置文件中的[`SILENCED_SYSTEM_CHECKS`](../ref/settings.html#std:setting-SILENCED_SYSTEM_CHECKS) 設置,來隱藏特定的警告。
[_系統檢查參考_](../ref/checks.html)中列出了所有Django可執行的所有檢查。
## 編寫你自己的檢查
這個框架十分靈活,允許你編寫函數,執行任何其他類型的所需檢查。下面是一個樁(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`參數用于進一步的擴展。
### 消息
這個函數必須返回消息的列表。如果檢查的結果中沒有發現問題,檢查函數必須返回一個空列表。
_class _`CheckMessage`(_level_, _msg_, _hint_, _obj=None_, _id=None_)
由檢查方法產生的警告和錯誤必須是[`CheckMessage`](#django.core.checks.CheckMessage "django.core.checks.CheckMessage")的示例。[`CheckMessage`](#django.core.checks.CheckMessage "django.core.checks.CheckMessage")的實例封裝了一個可報告的錯誤或者警告。它同時也提供了可應用到消息的上下文或者提示,以及一個用于過濾的唯一的標識符。
它的概念非常類似于[_消息框架_](../ref/contrib/messages.html)或者 [_日志框架_](logging.html)中的消息。消息使用表明其嚴重性的`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 letters
`CEWID`, 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`](../ref/django-admin.html#django-admin-option---deploy) 選項傳遞給[`check`](../ref/django-admin.html#django-admin-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`](db/managers.html#django.db.models.Manager "django.db.models.Manager")的子類上執行同樣的方法。
如果你想要向模型類添加檢查,方法也_大致_相同:唯一的不同是檢查是類方法,并不是實例方法:
```
class MyModel(models.Model):
@classmethod
def check(cls, **kwargs):
errors = super(MyModel, cls).check(**kwargs)
# ... your own checks ...
return errors
```
> 譯者:[Django 文檔協作翻譯小組](http://python.usyiyi.cn/django/index.html),原文:[System check framework](https://docs.djangoproject.com/en/1.8/topics/checks/)。
>
> 本文以 [CC BY-NC-SA 3.0](http://creativecommons.org/licenses/by-nc-sa/3.0/cn/) 協議發布,轉載請保留作者署名和文章出處。
>
> [Django 文檔協作翻譯小組](http://python.usyiyi.cn/django/index.html)人手緊缺,有興趣的朋友可以加入我們,完全公益性質。交流群:467338606。
- 新手入門
- 從零開始
- 概覽
- 安裝
- 教程
- 第1部分:模型
- 第2部分:管理站點
- 第3部分:視圖和模板
- 第4部分:表單和通用視圖
- 第5部分:測試
- 第6部分:靜態文件
- 高級教程
- 如何編寫可重用的應用
- 為Django編寫首個補丁
- 模型層
- 模型
- 模型語法
- 元選項
- 模型類
- 查詢集
- 執行查詢
- 查找表達式
- 模型的實例
- 實例方法
- 訪問關聯對象
- 遷移
- 模式編輯器
- 編寫遷移
- 高級
- 管理器
- 原始的SQL查詢
- 聚合
- 多數據庫
- 自定義查找
- 條件表達式
- 數據庫函數
- 其它
- 遺留的數據庫
- 提供初始數據
- 優化數據庫訪問
- 視圖層
- 基礎
- URL配置
- 視圖函數
- 快捷函數
- 裝飾器
- 參考
- 內建的視圖
- TemplateResponse 對象
- 文件上傳
- 概覽
- File 對象
- 儲存API
- 管理文件
- 自定義存儲
- 基于類的視圖
- 概覽
- 內建顯示視圖
- 內建編輯視圖
- API參考
- 分類索引
- 高級
- 生成 CSV
- 生成 PDF
- 中間件
- 概覽
- 內建的中間件類
- 模板層
- 基礎
- 面向設計師
- 語言概覽
- 人性化
- 面向程序員
- 表單
- 基礎
- 概覽
- 表單API
- 內建的Widget
- 高級
- 整合媒體
- 開發過程
- 設置
- 概覽
- 應用程序
- 異常
- 概覽
- django-admin 和 manage.py
- 添加自定義的命令
- 測試
- 介紹
- 部署
- 概述
- WSGI服務器
- 部署靜態文件
- 通過email追蹤代碼錯誤
- Admin
- 管理操作
- 管理文檔生成器
- 安全
- 安全概述
- 說明Django中的安全問題
- 點擊劫持保護
- 加密簽名
- 國際化和本地化
- 概述
- 本地化WEB UI格式化輸入
- “本地特色”
- 常見的網站應用工具
- 認證
- 概覽
- 使用認證系統
- 密碼管理
- 日志
- 分頁
- 會話
- 數據驗證
- 其它核心功能
- 按需內容處理
- 重定向
- 信號
- 系統檢查框架