django-verification
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDjango Verification Loop
Django 验证流程
Run before PRs, after major changes, and pre-deploy to ensure Django application quality and security.
在提交PR、完成重大变更以及部署前运行,以确保Django应用的质量与安全性。
When to Activate
适用场景
- Before opening a pull request for a Django project
- After major model changes, migration updates, or dependency upgrades
- Pre-deployment verification for staging or production
- Running full environment → lint → test → security → deploy readiness pipeline
- Validating migration safety and test coverage
- 为Django项目提交PR前
- 完成模型重大变更、迁移更新或依赖升级后
- 预发布环境或生产环境的部署前验证
- 运行完整的环境检查→代码扫描→测试→安全检查→部署就绪流水线
- 验证迁移安全性与测试覆盖率
Phase 1: Environment Check
阶段1:环境检查
bash
undefinedbash
undefinedVerify Python version
Verify Python version
python --version # Should match project requirements
python --version # Should match project requirements
Check virtual environment
Check virtual environment
which python
pip list --outdated
which python
pip list --outdated
Verify environment variables
Verify environment variables
python -c "import os; import environ; print('DJANGO_SECRET_KEY set' if os.environ.get('DJANGO_SECRET_KEY') else 'MISSING: DJANGO_SECRET_KEY')"
If environment is misconfigured, stop and fix.python -c "import os; import environ; print('DJANGO_SECRET_KEY set' if os.environ.get('DJANGO_SECRET_KEY') else 'MISSING: DJANGO_SECRET_KEY')"
如果环境配置错误,请停止并修复。Phase 2: Code Quality & Formatting
阶段2:代码质量与格式检查
bash
undefinedbash
undefinedType checking
Type checking
mypy . --config-file pyproject.toml
mypy . --config-file pyproject.toml
Linting with ruff
Linting with ruff
ruff check . --fix
ruff check . --fix
Formatting with black
Formatting with black
black . --check
black . # Auto-fix
black . --check
black . # Auto-fix
Import sorting
Import sorting
isort . --check-only
isort . # Auto-fix
isort . --check-only
isort . # Auto-fix
Django-specific checks
Django-specific checks
python manage.py check --deploy
Common issues:
- Missing type hints on public functions
- PEP 8 formatting violations
- Unsorted imports
- Debug settings left in production configurationpython manage.py check --deploy
常见问题:
- 公共函数缺少类型提示
- 违反PEP 8格式规范
- 导入语句未排序
- 生产配置中保留了调试设置Phase 3: Migrations
阶段3:迁移检查
bash
undefinedbash
undefinedCheck for unapplied migrations
Check for unapplied migrations
python manage.py showmigrations
python manage.py showmigrations
Create missing migrations
Create missing migrations
python manage.py makemigrations --check
python manage.py makemigrations --check
Dry-run migration application
Dry-run migration application
python manage.py migrate --plan
python manage.py migrate --plan
Apply migrations (test environment)
Apply migrations (test environment)
python manage.py migrate
python manage.py migrate
Check for migration conflicts
Check for migration conflicts
python manage.py makemigrations --merge # Only if conflicts exist
Report:
- Number of pending migrations
- Any migration conflicts
- Model changes without migrationspython manage.py makemigrations --merge # Only if conflicts exist
报告内容:
- 待应用的迁移数量
- 任何迁移冲突
- 未生成迁移的模型变更Phase 4: Tests + Coverage
阶段4:测试与覆盖率
bash
undefinedbash
undefinedRun all tests with pytest
Run all tests with pytest
pytest --cov=apps --cov-report=html --cov-report=term-missing --reuse-db
pytest --cov=apps --cov-report=html --cov-report=term-missing --reuse-db
Run specific app tests
Run specific app tests
pytest apps/users/tests/
pytest apps/users/tests/
Run with markers
Run with markers
pytest -m "not slow" # Skip slow tests
pytest -m integration # Only integration tests
pytest -m "not slow" # Skip slow tests
pytest -m integration # Only integration tests
Coverage report
Coverage report
open htmlcov/index.html
Report:
- Total tests: X passed, Y failed, Z skipped
- Overall coverage: XX%
- Per-app coverage breakdown
Coverage targets:
| Component | Target |
|-----------|--------|
| Models | 90%+ |
| Serializers | 85%+ |
| Views | 80%+ |
| Services | 90%+ |
| Overall | 80%+ |open htmlcov/index.html
报告内容:
- 测试总数:X通过,Y失败,Z跳过
- 整体覆盖率:XX%
- 各应用的覆盖率细分
覆盖率目标:
| 组件 | 目标 |
|-----------|--------|
| 模型 | 90%+ |
| 序列化器 | 85%+ |
| 视图 | 80%+ |
| 服务 | 90%+ |
| 整体 | 80%+ |Phase 5: Security Scan
阶段5:安全扫描
bash
undefinedbash
undefinedDependency vulnerabilities
Dependency vulnerabilities
pip-audit
safety check --full-report
pip-audit
safety check --full-report
Django security checks
Django security checks
python manage.py check --deploy
python manage.py check --deploy
Bandit security linter
Bandit security linter
bandit -r . -f json -o bandit-report.json
bandit -r . -f json -o bandit-report.json
Secret scanning (if gitleaks is installed)
Secret scanning (if gitleaks is installed)
gitleaks detect --source . --verbose
gitleaks detect --source . --verbose
Environment variable check
Environment variable check
python -c "from django.core.exceptions import ImproperlyConfigured; from django.conf import settings; settings.DEBUG"
Report:
- Vulnerable dependencies found
- Security configuration issues
- Hardcoded secrets detected
- DEBUG mode status (should be False in production)python -c "from django.core.exceptions import ImproperlyConfigured; from django.conf import settings; settings.DEBUG"
报告内容:
- 发现的易受攻击依赖
- 安全配置问题
- 检测到的硬编码密钥
- DEBUG模式状态(生产环境应设为False)Phase 6: Django Management Commands
阶段6:Django管理命令检查
bash
undefinedbash
undefinedCheck for model issues
Check for model issues
python manage.py check
python manage.py check
Collect static files
Collect static files
python manage.py collectstatic --noinput --clear
python manage.py collectstatic --noinput --clear
Create superuser (if needed for tests)
Create superuser (if needed for tests)
echo "from apps.users.models import User; User.objects.create_superuser('admin@example.com', 'admin')" | python manage.py shell
echo "from apps.users.models import User; User.objects.create_superuser('admin@example.com', 'admin')" | python manage.py shell
Database integrity
Database integrity
python manage.py check --database default
python manage.py check --database default
Cache verification (if using Redis)
Cache verification (if using Redis)
python -c "from django.core.cache import cache; cache.set('test', 'value', 10); print(cache.get('test'))"
undefinedpython -c "from django.core.cache import cache; cache.set('test', 'value', 10); print(cache.get('test'))"
undefinedPhase 7: Performance Checks
阶段7:性能检查
bash
undefinedbash
undefinedDjango Debug Toolbar output (check for N+1 queries)
Django Debug Toolbar output (check for N+1 queries)
Run in dev mode with DEBUG=True and access a page
Run in dev mode with DEBUG=True and access a page
Look for duplicate queries in SQL panel
Look for duplicate queries in SQL panel
Query count analysis
Query count analysis
django-admin debugsqlshell # If django-debug-sqlshell installed
django-admin debugsqlshell # If django-debug-sqlshell installed
Check for missing indexes
Check for missing indexes
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
Report:
- Number of queries per page (should be < 50 for typical pages)
- Missing database indexes
- Duplicate queries detectedpython 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)
- 缺失的数据库索引
- 检测到的重复查询Phase 8: Static Assets
阶段8:静态资源检查
bash
undefinedbash
undefinedCheck for npm dependencies (if using npm)
Check for npm dependencies (if using npm)
npm audit
npm audit fix
npm audit
npm audit fix
Build static files (if using webpack/vite)
Build static files (if using webpack/vite)
npm run build
npm run build
Verify static files
Verify static files
ls -la staticfiles/
python manage.py findstatic css/style.css
undefinedls -la staticfiles/
python manage.py findstatic css/style.css
undefinedPhase 9: Configuration Review
阶段9:配置审查
python
undefinedpython
undefinedRun in Python shell to verify settings
Run in Python shell to verify settings
python manage.py shell << EOF
from django.conf import settings
import os
python manage.py shell << EOF
from django.conf import settings
import os
Critical checks
Critical checks
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
undefinedchecks = {
'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
undefinedPhase 10: Logging Configuration
阶段10:日志配置检查
bash
undefinedbash
undefinedTest logging output
Test logging output
python manage.py shell << EOF
import logging
logger = logging.getLogger('django')
logger.warning('Test warning message')
logger.error('Test error message')
EOF
python manage.py shell << EOF
import logging
logger = logging.getLogger('django')
logger.warning('Test warning message')
logger.error('Test error message')
EOF
Check log files (if configured)
Check log files (if configured)
tail -f /var/log/django/django.log
undefinedtail -f /var/log/django/django.log
undefinedPhase 11: API Documentation (if DRF)
阶段11:API文档检查(若使用DRF)
bash
undefinedbash
undefinedGenerate schema
Generate schema
python manage.py generateschema --format openapi-json > schema.json
python manage.py generateschema --format openapi-json > schema.json
Validate schema
Validate schema
Check if schema.json is valid JSON
Check if schema.json is valid JSON
python -c "import json; json.load(open('schema.json'))"
python -c "import json; json.load(open('schema.json'))"
Access Swagger UI (if using drf-yasg)
Access Swagger UI (if using drf-yasg)
Visit http://localhost:8000/swagger/ in browser
Visit http://localhost:8000/swagger/ in browser
undefinedundefinedPhase 12: Diff Review
阶段12:差异审查
bash
undefinedbash
undefinedShow diff statistics
Show diff statistics
git diff --stat
git diff --stat
Show actual changes
Show actual changes
git diff
git diff
Show changed files
Show changed files
git diff --name-only
git diff --name-only
Check for common issues
Check for common issues
git diff | grep -i "todo|fixme|hack|xxx"
git diff | grep "print(" # Debug statements
git diff | grep "DEBUG = True" # Debug mode
git diff | grep "import pdb" # Debugger
Checklist:
- No debugging statements (print, pdb, breakpoint())
- No TODO/FIXME comments in critical code
- No hardcoded secrets or credentials
- Database migrations included for model changes
- Configuration changes documented
- Error handling present for external calls
- Transaction management where neededgit diff | grep -i "todo|fixme|hack|xxx"
git diff | grep "print(" # Debug statements
git diff | grep "DEBUG = True" # Debug mode
git diff | grep "import pdb" # Debugger
检查清单:
- 无调试语句(print、pdb、breakpoint())
- 关键代码中无TODO/FIXME注释
- 无硬编码密钥或凭证
- 模型变更已包含数据库迁移
- 配置变更已文档化
- 外部调用已添加错误处理
- 必要处已添加事务管理Output Template
输出模板
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: ⚠️ Fix pip-audit vulnerabilities before deploying
NEXT STEPS:
1. Update vulnerable dependencies
2. Re-run security scan
3. Deploy to staging for final testingDJANGO 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: ⚠️ Fix pip-audit vulnerabilities before deploying
NEXT STEPS:
1. Update vulnerable dependencies
2. Re-run security scan
3. Deploy to staging for final testingPre-Deployment Checklist
部署前检查清单
- All tests passing
- Coverage ≥ 80%
- No security vulnerabilities
- No unapplied migrations
- DEBUG = False in production settings
- SECRET_KEY properly configured
- ALLOWED_HOSTS set correctly
- Database backups enabled
- Static files collected and served
- Logging configured and working
- Error monitoring (Sentry, etc.) configured
- CDN configured (if applicable)
- Redis/cache backend configured
- Celery workers running (if applicable)
- HTTPS/SSL configured
- Environment variables documented
- 所有测试通过
- 覆盖率≥80%
- 无安全漏洞
- 无待应用的迁移
- 生产环境设置中DEBUG=False
- SECRET_KEY已正确配置
- ALLOWED_HOSTS已正确设置
- 已启用数据库备份
- 静态资源已收集并可提供服务
- 日志已配置并正常工作
- 已配置错误监控(如Sentry)
- 已配置CDN(如适用)
- 已配置Redis/缓存后端
- Celery worker已运行(如适用)
- 已配置HTTPS/SSL
- 环境变量已文档化
Continuous Integration
持续集成
GitHub Actions Example
GitHub Actions 示例
yaml
undefinedyaml
undefined.github/workflows/django-verification.yml
.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@v3undefinedname: 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@v3undefinedQuick Reference
快速参考
| Check | Command |
|---|---|
| Environment | |
| Type checking | |
| Linting | |
| Formatting | |
| Migrations | |
| Tests | |
| Security | |
| Django check | |
| Collectstatic | |
| Diff stats | |
Remember: Automated verification catches common issues but doesn't replace manual code review and testing in staging environment.
| 检查项 | 命令 |
|---|---|
| 环境检查 | |
| 类型检查 | |
| 代码扫描 | |
| 格式检查 | |
| 迁移检查 | |
| 测试运行 | |
| 安全扫描 | |
| Django配置检查 | |
| 静态资源收集 | |
| 差异统计 | |
注意:自动化验证可以发现常见问题,但无法替代人工代码审查和预发布环境中的测试。