Communitygithub.com

Django 验证循环

Django 项目的验证流程:迁移、代码检查、带覆盖率的测试、安全扫描以及发布或 PR 前的部署就绪检查。

Django 验证循环 是什么?

该技能为 Django 项目提供了一套完整的预部署和预合并验证流水线,覆盖从环境检查、代码质量、数据库迁移、测试覆盖率到安全扫描和配置审核的 12 个阶段。它支持本地手动执行和 CI(如 GitHub Actions)自动化运行,旨在帮助开发者在提交 PR 或发布版本前系统性地发现并修复常见问题,确保 Django 应用的质量与安全性。技能附带了详细的检查命令、预期输出示例以及一份输出报告模板,用户可据此快速定位问题并生成规范化的验证报告。

兼容平台~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/django-verification

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Django 验证循环 是做什么的?

在 PR 前、重大更改后以及预部署时运行,确保 Django 应用程序的质量和安全性。

何时激活

  • 为 Django 项目打开拉取请求之前
  • 在重大模型更改、迁移更新或依赖项升级之后
  • 预部署验证(针对暂存或生产环境)
  • 运行完整的环境 → 代码检查 → 测试 → 安全 → 部署就绪管道
  • 验证迁移安全性和测试覆盖率

阶段 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 调试工具栏输出(检查 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 验证报告
==========================

阶段 1:环境检查
  ✓ Python 3.11.5
  ✓ 虚拟环境已激活
  ✓ 所有环境变量已设置

阶段 2:代码质量
  ✓ mypy:无类型错误
  ✗ ruff:发现 3 个问题(已自动修复)
  ✓ black:无格式问题
  ✓ isort:导入已正确排序
  ✓ manage.py check:无问题

阶段 3:迁移
  ✓ 无未应用的迁移
  ✓ 无迁移冲突
  ✓ 所有模型都有迁移

阶段 4:测试 + 覆盖率
  测试:247 通过,0 失败,5 跳过
  覆盖率:
    总体:87%
    users:92%
    products:89%
    orders:85%
    payments:91%

阶段 5:安全扫描
  ✗ pip-audit:发现 2 个漏洞(需要修复)
  ✓ safety check:无问题
  ✓ bandit:无安全问题
  ✓ 未检测到密钥
  ✓ DEBUG = False

阶段 6:Django 命令
  ✓ collectstatic 已完成
  ✓ 数据库完整性 OK
  ✓ 缓存后端可访问

阶段 7:性能
  ✓ 未检测到 N+1 查询
  ✓ 数据库索引已配置
  ✓ 查询数量可接受

阶段 8:静态资产
  ✓ npm audit:无漏洞
  ✓ 资产构建成功
  ✓ 静态文件已收集

阶段 9:配置
  ✓ DEBUG = False
  ✓ SECRET_KEY 已配置
  ✓ ALLOWED_HOSTS 已设置
  ✓ HTTPS 已启用
  ✓ HSTS 已启用
  ✓ 数据库已配置

阶段 10:日志
  ✓ 日志已配置
  ✓ 日志文件可写

阶段 11:API 文档
  ✓ Schema 已生成
  ✓ Swagger UI 可访问

阶段 12:差异审查
  更改的文件:12
  +450,-120 行
  ✓ 无调试语句
  ✓ 无硬编码密钥
  ✓ 包含迁移

建议:警告:部署前请修复 pip-audit 漏洞

下一步:
1. 更新易受攻击的依赖项
2. 重新运行安全扫描
3. 部署到暂存环境进行最终测试

预部署检查清单

  • 所有测试通过
  • 覆盖率 ≥ 80%
  • 无安全漏洞
  • 无未应用的迁移
  • 生产设置中 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 .
代码检查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

请记住:自动化验证可以捕获常见问题,但不能替代手动代码审查和暂存环境中的测试。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

相关技能