Communitygithub.com

Django 验证循环

针对 Django 项目的验证循环:包括迁移、代码检查、带覆盖率的测试、安全扫描以及发布前的部署就绪检查。

Django 验证循环 是什么?

该技能定义了一个全面的 Django 验证循环(Verification Loop),旨在 PR 提交前、重大变更后或部署前自动运行。它包含从环境检查、代码质量(类型检查、格式化、导入排序)、Django 特有检查(如 `manage.py check --deploy`)、迁移验证、测试与覆盖率分析(支持 pytest)到安全扫描(pip-audit、bandit、gitLeaks)的完整流水线。支持 CI/CD 集成(提供 GitHub Actions 示例)并输出详细的验证报告。通过此技能,开发者可以确保 Django 项目的质量、安全和部署就绪性,减少人工审查遗漏。

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

在你喜欢的 AI 中提问

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

文档

Django 验证循环 是做什么的?

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

何时激活

  • 在提交 Django 项目的拉取请求之前
  • 在重大的模型变更、迁移更新或依赖升级之后
  • 在预部署验证(测试或生产环境)时
  • 运行完整的环境 → 代码检查 → 测试 → 安全 → 部署就绪流水线
  • 验证迁移安全性及测试覆盖率

第一阶段:环境检查

# 验证 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')"

如果环境配置错误,立即停止并修复。

第二阶段:代码质量与格式

# 类型检查
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 格式违规
  • 未排序的导入
  • 生产配置中遗留了调试设置

第三阶段:迁移

# 检查未应用的迁移
python manage.py showmigrations

# 创建缺失的迁移
python manage.py makemigrations --check

# 干运行迁移应用
python manage.py migrate --plan

# 应用迁移(测试环境)
python manage.py migrate

# 检查迁移冲突
python manage.py makemigrations --merge  # 仅在有冲突时

报告:

  • 待处理迁移数量
  • 任何迁移冲突
  • 模型变更但未生成迁移

第四阶段:测试 + 覆盖率

# 使用 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%
  • 每个应用的覆盖率细分

覆盖率目标:

组件目标
Models90%+
序列化器85%+
视图80%+
服务层90%+
总体80%+

第五阶段:安全扫描

# 依赖漏洞
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)

第六阶段: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'))"

第七阶段:性能检查

# 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)
  • 缺失的数据库索引
  • 检测到的重复查询

第八阶段:静态资源

# 检查 npm 依赖(如果使用 npm)
npm audit
npm audit fix

# 构建静态文件(如果使用 webpack/vite)
npm run build

# 验证静态文件
ls -la staticfiles/
python manage.py findstatic css/style.css

第九阶段:配置审查

# 在 Python shell 中运行以验证设置
python manage.py shell << EOF
from django.conf import settings
import os

# 关键检查
checks = {
    'DEBUG 为 False': not settings.DEBUG,
    'SECRET_KEY 已设置': bool(settings.SECRET_KEY and len(settings.SECRET_KEY) > 30),
    'ALLOWED_HOSTS 已设置': len(settings.ALLOWED_HOSTS) > 0,
    'HTTPS 已启用': getattr(settings, 'SECURE_SSL_REDIRECT', False),
    'HSTS 已启用': getattr(settings, 'SECURE_HSTS_SECONDS', 0) > 0,
    '数据库已配置': settings.DATABASES['default']['ENGINE'] != 'django.db.backends.sqlite3',
}

for check, result in checks.items():
    status = '✓' if result else '✗'
    print(f"{status} {check}")
EOF

第十阶段:日志配置

# 测试日志输出
python manage.py shell << EOF
import logging
logger = logging.getLogger('django')
logger.warning('测试警告消息')
logger.error('测试错误消息')
EOF

# 检查日志文件(如果已配置)
tail -f /var/log/django/django.log

第十一阶段: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/

第十二阶段:差异审查

# 显示差异统计

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 验证报告
==========================

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

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

第三阶段:迁移
  ✓ 无不应用迁移
  ✓ 无迁移冲突
  ✓ 所有模型都有迁移

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

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

第六阶段:Django 命令
  ✓ collectstatic 已完成
  ✓ 数据库完整性正常
  ✓ 缓存后端可访问

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

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

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

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

第十一阶段:API 文档
  ✓ 模式已生成
  ✓ Swagger UI 可访问

第十二阶段:差异审查
  变更文件: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 验证

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: 设置 Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'

      - name: 缓存 pip
        uses: actions/cache@v3
        with:
          path: ~/.cache/pip
          key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}

      - name: 安装依赖
        run: |
          pip install -r requirements.txt
          pip install ruff black mypy pytest pytest-django pytest-cov bandit safety pip-audit

      - name: 代码质量检查
        run: |
          ruff check .
          black . --check
          isort . --check-only
          mypy .

      - name: 安全扫描
        run: |
          bandit -r . -f json -o bandit-report.json
          safety check --full-report
          pip-audit

      - name: 运行测试
        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: 上传覆盖率
        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/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

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.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

相关技能