Django 驗證循環
在 PR 前、重大變更後以及部署前執行,確保 Django 應用程式的品質與安全性。
何時啟用
- 在為 Django 專案開啟 Pull Request 之前
- 在重大的模型變更、遷移更新或依賴套件升級之後
- 針對暫存環境或正式環境的部署前驗證
- 執行完整的環境 → 語法檢查 → 測試 → 安全 → 部署就緒流程
- 驗證遷移安全性與測試覆蓋率
階段 1:環境檢查
# 確認 Python 版本
python --version # 應符合專案需求
# 檢查虛擬環境
which python
pip list --outdated
# 驗證環境變數
python -c "import os; import environ; print('DJANGO_SECRET_KEY set' if os.environ.get('DJANGO_SECRET_KEY') else 'MISSING: DJANGO_SECRET_KEY')"
若環境設定有誤,請先修正再繼續。
階段 2:程式碼品質與格式化
# 型別檢查
mypy . --config-file pyproject.toml
# 使用 ruff 進行語法檢查
ruff check . --fix
# 使用 black 進行格式化
black . --check
black . # 自動修正
# 匯入排序
isort . --check-only
isort . # 自動修正
# Django 專用檢查
python manage.py check --deploy
常見問題:
- 公有函式缺少型別提示
- PEP 8 格式違規
- 未排序的匯入
- 在正式環境組態中遺留除錯設定
階段 3:遷移
# 檢查未套用的遷移
python manage.py showmigrations
# 建立遺漏的遷移
python manage.py makemigrations --check
# 預覽遷移套用計畫
python manage.py migrate --plan
# 套用遷移(測試環境)
python manage.py migrate
# 檢查遷移衝突
python manage.py makemigrations --merge # 僅在存在衝突時執行
報告:
- 待處理的遷移數量
- 任何遷移衝突
- 模型變更但無對應遷移
階段 4:測試與覆蓋率
# 執行所有測試(使用 pytest)
pytest --cov=apps --cov-report=html --cov-report=term-missing --reuse-db
# 執行特定應用程式的測試
pytest apps/users/tests/
# 使用標記執行測試
pytest -m "not slow" # 跳過慢速測試
pytest -m integration # 僅執行整合測試
# 覆蓋率報告
open htmlcov/index.html
報告:
- 總測試數:X 通過,Y 失敗,Z 跳過
- 整體覆蓋率:XX%
- 各應用程式的覆蓋率細項
覆蓋率目標:
| 元件 | 目標 |
|---|---|
| 模型 | 90%+ |
| 序列化器 | 85%+ |
| 視圖 | 80%+ |
| 服務層 | 90%+ |
| 整體 | 80%+ |
階段 5:安全掃描
# 依賴套件漏洞
pip-audit
safety check --full-report
# Django 安全檢查
python manage.py check --deploy
# Bandit 安全語法檢查器
bandit -r . -f json -o bandit-report.json
# 秘密掃描(若已安裝 gitleaks)
gitleaks detect --source . --verbose
# 環境變數檢查
python -c "from django.core.exceptions import ImproperlyConfigured; from django.conf import settings; settings.DEBUG"
報告:
- 發現的漏洞依賴套件
- 安全性組態問題
- 檢測到的硬編碼秘密
- DEBUG 模式狀態(正式環境應為 False)
階段 6:Django 管理指令
# 檢查模型問題
python manage.py check
# 收集靜態檔案
python manage.py collectstatic --noinput --clear
# 建立超級使用者(測試用)
echo "from apps.users.models import User; User.objects.create_superuser('[email protected]', 'admin')" | python manage.py shell
# 資料庫完整性
python manage.py check --database default
# 快取驗證(若使用 Redis)
python -c "from django.core.cache import cache; cache.set('test', 'value', 10); print(cache.get('test'))"
階段 7:效能檢查
# Django Debug Toolbar 輸出(檢查 N+1 查詢)
# 在開發模式下以 DEBUG=True 執行並存取頁面
# 查看 SQL 面板中的重複查詢
# 查詢數量分析
django-admin debugsqlshell # 若已安裝 django-debug-sqlshell
# 檢查遺漏的索引
python manage.py shell << EOF
from django.db import connection
with connection.cursor() as cursor:
cursor.execute("SELECT table_name, index_name FROM information_schema.statistics WHERE table_schema = 'public'")
print(cursor.fetchall())
EOF
報告:
- 每頁查詢數量(典型頁面應少於 50 個)
- 遺漏的資料庫索引
- 偵測到的重複查詢
階段 8:靜態資產
# 檢查 npm 依賴套件(若使用 npm)
npm audit
npm audit fix
# 建置靜態檔案(若使用 webpack/vite)
npm run build
# 驗證靜態檔案
ls -la staticfiles/
python manage.py findstatic css/style.css
階段 9:組態審查
# 在 Python shell 中執行以驗證設定
python manage.py shell << EOF
from django.conf import settings
import os
# 關鍵檢查
checks = {
'DEBUG is False': not settings.DEBUG,
'SECRET_KEY set': bool(settings.SECRET_KEY and len(settings.SECRET_KEY) > 30),
'ALLOWED_HOSTS set': len(settings.ALLOWED_HOSTS) > 0,
'HTTPS enabled': getattr(settings, 'SECURE_SSL_REDIRECT', False),
'HSTS enabled': getattr(settings, 'SECURE_HSTS_SECONDS', 0) > 0,
'Database configured': settings.DATABASES['default']['ENGINE'] != 'django.db.backends.sqlite3',
}
for check, result in checks.items():
status = '✓' if result else '✗'
print(f"{status} {check}")
EOF
階段 10:日誌設定
# 測試日誌輸出
python manage.py shell << EOF
import logging
logger = logging.getLogger('django')
logger.warning('Test warning message')
logger.error('Test error message')
EOF
# 檢查日誌檔案(若有設定)
tail -f /var/log/django/django.log
階段 11:API 文件(若使用 DRF)
# 產生架構
python manage.py generateschema --format openapi-json > schema.json
# 驗證架構
# 檢查 schema.json 是否為有效的 JSON
python -c "import json; json.load(open('schema.json'))"
# 存取 Swagger UI(若使用 drf-yasg)
# 在瀏覽器中前往 http://localhost:8000/swagger/
階段 12:差異審查
# 顯示差異統計
it diff --stat
# 顯示實際變更
git diff
# 顯示變更的檔案
git diff --name-only
# 檢查常見問題
git diff | grep -i "todo\|fixme\|hack\|xxx"
git diff | grep "print(" # 除錯敘述
git diff | grep "DEBUG = True" # 除錯模式
git diff | grep "import pdb" # 除錯器
檢查清單:
- 無除錯敘述(print、pdb、breakpoint())
- 關鍵程式碼中無 TODO/FIXME 註解
- 無硬編碼的秘密或憑證
- 模型變更包含資料庫遷移
- 組態變更已記錄
- 外部呼叫有錯誤處理
- 必要時有事務管理
輸出範本
DJANGO VERIFICATION REPORT
==========================
Phase 1: Environment Check
✓ Python 3.11.5
✓ Virtual environment active
✓ All environment variables set
Phase 2: Code Quality
✓ mypy: No type errors
✗ ruff: 3 issues found (auto-fixed)
✓ black: No formatting issues
✓ isort: Imports properly sorted
✓ manage.py check: No issues
Phase 3: Migrations
✓ No unapplied migrations
✓ No migration conflicts
✓ All models have migrations
Phase 4: Tests + Coverage
Tests: 247 passed, 0 failed, 5 skipped
Coverage:
Overall: 87%
users: 92%
products: 89%
orders: 85%
payments: 91%
Phase 5: Security Scan
✗ pip-audit: 2 vulnerabilities found (fix required)
✓ safety check: No issues
✓ bandit: No security issues
✓ No secrets detected
✓ DEBUG = False
Phase 6: Django Commands
✓ collectstatic completed
✓ Database integrity OK
✓ Cache backend reachable
Phase 7: Performance
✓ No N+1 queries detected
✓ Database indexes configured
✓ Query count acceptable
Phase 8: Static Assets
✓ npm audit: No vulnerabilities
✓ Assets built successfully
✓ Static files collected
Phase 9: Configuration
✓ DEBUG = False
✓ SECRET_KEY configured
✓ ALLOWED_HOSTS set
✓ HTTPS enabled
✓ HSTS enabled
✓ Database configured
Phase 10: Logging
✓ Logging configured
✓ Log files writable
Phase 11: API Documentation
✓ Schema generated
✓ Swagger UI accessible
Phase 12: Diff Review
Files changed: 12
+450, -120 lines
✓ No debug statements
✓ No hardcoded secrets
✓ Migrations included
RECOMMENDATION: WARNING: Fix pip-audit vulnerabilities before deploying
NEXT STEPS:
1. Update vulnerable dependencies
2. Re-run security scan
3. Deploy to staging for final testing
部署前檢查清單
- 所有測試通過
- 覆蓋率 ≥ 80%
- 無安全性漏洞
- 無未套用的遷移
- 正式環境設定中 DEBUG = False
- SECRET_KEY 已正確設定
- ALLOWED_HOSTS 已正確設定
- 已啟用資料庫備份
- 靜態檔案已收集並提供服務
- 日誌已設定並運作
- 錯誤監控(如 Sentry)已設定
- CDN 已設定(如適用)
- Redis/快取後端已設定
- Celery worker 正在執行(如適用)
- HTTPS/SSL 已設定
- 環境變數已記錄
持續整合
GitHub Actions 範例
# .github/workflows/django-verification.yml
name: Django Verification
on: [push, pull_request]
jobs:
verify:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:14
env:
POSTGRES_PASSWORD: postgres
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Cache pip
uses: actions/cache@v3
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install ruff black mypy pytest pytest-django pytest-cov bandit safety pip-audit
- name: Code quality checks
run: |
ruff check .
black . --check
isort . --check-only
mypy .
- name: Security scan
run: |
bandit -r . -f json -o bandit-report.json
safety check --full-report
pip-audit
- name: Run tests
env:
DATABASE_URL: postgres://postgres:postgres@localhost:5432/test
DJANGO_SECRET_KEY: test-secret-key
run: |
pytest --cov=apps --cov-report=xml --cov-report=term-missing
- name: Upload coverage
uses: codecov/codecov-action@v3
快速參考
| 檢查項目 | 指令 |
|---|---|
| 環境 | python --version |
| 型別檢查 | mypy . |
| 語法檢查 | ruff check . |
| 格式化 | black . --check |
| 遷移 | python manage.py makemigrations --check |
| 測試 | pytest --cov=apps |
| 安全性 | pip-audit && bandit -r . |
| Django 檢查 | python manage.py check --deploy |
| 收集靜態檔案 | python manage.py collectstatic --noinput |
| 差異統計 | git diff --stat |
請記住:自動化驗證能捕捉常見問題,但無法取代人工程式碼審查和在暫存環境中的測試。