1---2name: python-backend3description: Use for Python backend services — FastAPI, Django/DRF, Flask — async patterns, Pydantic, ORM, auth, testing. Triggers — Python server code, pyproject.toml, 'fastapi', 'django', 'flask'.4---56# Python Backend Development78## When to use9- Writing REST or GraphQL APIs with FastAPI, Django REST Framework, or Flask10- Designing Pydantic models, serialisers, or schema validation11- Implementing authentication (OAuth2, JWT, session) or permission layers12- Integrating SQLAlchemy, Django ORM, or raw psycopg queries13- Writing tests with pytest (sync and async)14- Profiling and fixing slow endpoints or memory growth1516## Workflow17181. **Classify** — sync Django/DRF vs async FastAPI, type of data access, auth model.192. **Set up the environment**:20 - Python 3.11+ with `pyproject.toml` (PEP 517/518).21 - Dependency manager: `uv` (fast) or `poetry`. Avoid bare `pip install` in CI.22 - Virtual env: always isolated — never install into system Python.233. **Scaffold**:24 - FastAPI: `app = FastAPI()` in `main.py`; split into `routers/`, `models/`, `schemas/`, `deps/`, `core/`.25 - Django: `django-admin startproject`; apps map to bounded contexts.264. **Define Pydantic schemas (FastAPI) or serialisers (DRF) before handlers** — they document and enforce the contract.275. **Implement business logic in service functions**, not in view/route handlers. Handlers parse → call service → serialise response.286. **Database access**:29 - FastAPI + SQLAlchemy async: use `AsyncSession` with `async with session.begin()`.30 - Django ORM: `select_related` / `prefetch_related` to prevent N+1; use `transaction.atomic` for multi-step writes.317. **Auth**: FastAPI uses `Depends(get_current_user)`; DRF uses `permission_classes`. Validate JWT with `python-jose` or `authlib`; never decode without signature verification.328. **Error handling**: FastAPI `HTTPException`; DRF `ValidationError` / `APIException`; Flask `@app.errorhandler`. Always return structured JSON errors.339. **Test**: `pytest` + `httpx.AsyncClient` for FastAPI; Django `TestClient`; use `pytest-anyio` for async tests. Cover happy path, 422/400 validation, and auth failure.3410. **Harden**: CORS allowlist, rate limiting (`slowapi` / Django Ratelimit), request size limits, SQL injection prevention via ORM/parameterised queries.3511. **Audit** against .claude/checklists/security.md and .claude/checklists/performance.md before deploying.3637## Standards3839### Type safety40- Use Python 3.10+ type hints everywhere: `def get_user(user_id: int) -> UserSchema:`.41- Run `mypy --strict` or `pyright` in CI.42- Pydantic v2 (`model_config = ConfigDict(strict=True)`) for FastAPI schemas.4344### FastAPI specifics45- All path/query/body parameters must be typed; Pydantic validates automatically.46- Use `Depends()` for DB sessions, auth, pagination — not global variables.47- Background tasks (`BackgroundTasks` or Celery) for anything not in the critical path.48- Mount routers with prefix and tags: `app.include_router(users.router, prefix="/users", tags=["users"])`.4950### Django/DRF specifics51- Use `get_object_or_404` not bare `Model.objects.get` — prevents 500 on missing records.52- ViewSets for CRUD resources; `APIView` for custom endpoints.53- `settings.py` split: `base.py`, `local.py`, `production.py`; use `django-environ` for env vars.54- Never use `DEBUG=True` in production; `ALLOWED_HOSTS` must be explicit.5556### Database (SQLAlchemy)57- Always use parameterised queries — never `f"SELECT ... WHERE id={user_id}"`.58- Define models with explicit `__tablename__`, column types, and constraints.59- Async sessions must be closed; use context managers or `async_scoped_session`.60- Alembic for migrations; check migration against production schema in CI.6162### Do not63- Do not use mutable default arguments (`def f(items=[])`).64- Do not catch bare `Exception` without re-raising or logging with full traceback.65- Do not use `pickle` for untrusted data deserialization.66- Do not import at module level what belongs behind a function scope (avoids circular imports and slow startup).67- Do not store secrets in `settings.py`; load from environment and validate at startup.6869## Common mistakes to avoid7071| Mistake | Fix |72|---|---|73| Blocking I/O in an async FastAPI handler | Use `await asyncio.to_thread(sync_fn)` or an async library. |74| SQLAlchemy lazy load outside session scope | Either `expire_on_commit=False`, eager-load, or keep the session open. |75| Django ORM queries in serialiser `to_representation` | Move queries to the view with `select_related`; serialisers must be query-free. |76| Returning Python exceptions as 500 with stack trace | Catch in error handler; return `{"detail": "..."}` with appropriate status. |77| Tests hitting the production database | Use `pytest-django`'s `@pytest.mark.django_db` with a test DB, or SQLite in-memory. |78| Circular import in FastAPI `Depends` chain | Restructure deps into a `deps.py` module imported by both sides. |7980## Output format8182- New endpoint: route function + Pydantic schema + service function, all typed.83- Module layout: directory tree showing `routers/`, `schemas/`, `services/`, `models/`, `tests/`.84- Test file: `pytest` functions covering success, 422 validation error, and 401 auth failure.85- Migration: Alembic `upgrade`/`downgrade` functions with comments on intent.8687## Related checklists88- .claude/checklists/security.md89- .claude/checklists/performance.md90- .claude/checklists/qa.md9192## Related agents93- .claude/agents/core/orchestrator.md94- .claude/agents/engineering/devops-engineer.md