SKILL.md
readonlyread-only
name
django-verification
description
Django 專案的驗證流程:遷移、程式碼檢查、含覆蓋率的測試、安全掃描,以及在發佈或 PR 前檢查部署就緒狀態。
Django 驗證流程
在 PR 前、重大變更後及部署前執行,以確保 Django 應用程式的品質與安全性。
何時啟用
- 為 Django 專案開立 Pull Request 之前
- 重大模型變更、遷移更新或相依套件升級之後
- 預備部署至 Staging 或 Production 前的驗證
- 執行完整環境 → 程式碼檢查 → 測試 → 安全 → 部署就緒的管線
- 驗證遷移安全性與測試覆蓋率
階段 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 進行 lint
ruff check . --fix
# 使用 black 格式化
black . --check
black . # 自動修正
# 匯入排序
isort . --check-only
isort . # 自動修正
# Django 特定檢查
python manage.py check --deploy
常見問題:
- 公開函式缺少型別提示
- PEP 8 格式化違規
- 未排序的匯入
- Production 設定中遺留 Debug 設定
階段 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%
- 各應用程式覆蓋率細項
覆蓋率目標:
| 元件 | 目標 |
|---|---|
| Models | 90%+ |
| Serializers | 85%+ |
| Views | 80%+ |
| Services | 90%+ |
| 整體 | 80%+ |
階段 5:安全掃描
# 相依套件漏洞
pip-audit
safety check --full-report
# Django 安全檢查
python manage.py check --deploy
# Bandit 安全 linter
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 模式狀態(Production 應為 False)
階段 6:Django 管理指令
# 檢查模型問題
python manage.py check
# 收集靜態檔案
python manage.py collectstatic --noinput --clear
# 建立超級使用者(若測試需要)
echo "from apps.users.models import User; User.objects.create_superuser('admin@example.com', '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)
# 產生 Schema
python manage.py generateschema --format openapi-json > schema.json
# 驗證 Schema
# 檢查 schema.json 是否為有效的 JSON
python -c "import json; json.load(open('schema.json'))"
# 存取 Swagger UI(若使用 drf-yasg)
# 在瀏覽器中開啟 http://localhost:8000/swagger/
階段 12:差異審查
# 顯示差異統計
git 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%
- [ ] 無安全漏洞
- [ ] 無未套用的遷移
- [ ] Production 設定中 DEBUG = False
- [ ] SECRET_KEY 已正確設定
- [ ] ALLOWED_HOSTS 已正確設定
- [ ] 資料庫備份已啟用
- [ ] 靜態檔案已收集並提供服務
- [ ] 日誌已設定且正常運作
- [ ] 錯誤監控(如 Sentry)已設定
- [ ] CDN 已設定(若適用)
- [ ] Redis/快取後端已設定
- [ ] Celery 工作者正在執行(若適用)
- [ ] 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 . |
| Linting | 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 |
請記住:自動化驗證能捕捉常見問題,但無法取代人工程式碼審查與在 Staging 環境中的測試。






