Python backend
Skill muxammadmamajonov/dot-claude/.claude/skills/python-backend
Use for Python backend services — FastAPI, Django/DRF, Flask — async patterns, Pydantic, ORM, auth, testing. Triggers — Python server code, pyproject.toml, 'fastapi', 'django', 'flask'.From its SKILL.md
npx -y skills add muxammadmamajonov/dot-claude --skill python-backendAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
One thing to look at
- 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
SKILL.md
5.4 KB, ~1.3k tokens by cl100k_base, as published. Nobody here has run it
Python Backend Development
When to use
- Writing REST or GraphQL APIs with FastAPI, Django REST Framework, or Flask
- Designing Pydantic models, serialisers, or schema validation
- Implementing authentication (OAuth2, JWT, session) or permission layers
- Integrating SQLAlchemy, Django ORM, or raw psycopg queries
- Writing tests with pytest (sync and async)
- Profiling and fixing slow endpoints or memory growth
Workflow
- Classify — sync Django/DRF vs async FastAPI, type of data access, auth model.
- Set up the environment:
- Python 3.11+ with
pyproject.toml(PEP 517/518). - Dependency manager:
uv(fast) orpoetry. Avoid barepip installin CI. - Virtual env: always isolated — never install into system Python.
- Python 3.11+ with
- Scaffold:
- FastAPI:
app = FastAPI()inmain.py; split intorouters/,models/,schemas/,deps/,core/. - Django:
django-admin startproject; apps map to bounded contexts.
- FastAPI:
- Define Pydantic schemas (FastAPI) or serialisers (DRF) before handlers — they document and enforce the contract.
- Implement business logic in service functions, not in view/route handlers. Handlers parse → call service → serialise response.
- Database access:
- FastAPI + SQLAlchemy async: use
AsyncSessionwithasync with session.begin(). - Django ORM:
select_related/prefetch_relatedto prevent N+1; usetransaction.atomicfor multi-step writes.
- FastAPI + SQLAlchemy async: use
- Auth: FastAPI uses
Depends(get_current_user); DRF usespermission_classes. Validate JWT withpython-joseorauthlib; never decode without signature verification. - Error handling: FastAPI
HTTPException; DRFValidationError/APIException; Flask@app.errorhandler. Always return structured JSON errors. - Test:
pytest+httpx.AsyncClientfor FastAPI; DjangoTestClient; usepytest-anyiofor async tests. Cover happy path, 422/400 validation, and auth failure. - Harden: CORS allowlist, rate limiting (
slowapi/ Django Ratelimit), request size limits, SQL injection prevention via ORM/parameterised queries. - Audit against .claude/checklists/security.md and .claude/checklists/performance.md before deploying.
Standards
Type safety
- Use Python 3.10+ type hints everywhere:
def get_user(user_id: int) -> UserSchema:. - Run
mypy --strictorpyrightin CI. - Pydantic v2 (
model_config = ConfigDict(strict=True)) for FastAPI schemas.
FastAPI specifics
- All path/query/body parameters must be typed; Pydantic validates automatically.
- Use
Depends()for DB sessions, auth, pagination — not global variables. - Background tasks (
BackgroundTasksor Celery) for anything not in the critical path. - Mount routers with prefix and tags:
app.include_router(users.router, prefix="/users", tags=["users"]).
Django/DRF specifics
- Use
get_object_or_404not bareModel.objects.get— prevents 500 on missing records. - ViewSets for CRUD resources;
APIViewfor custom endpoints. settings.pysplit:base.py,local.py,production.py; usedjango-environfor env vars.- Never use
DEBUG=Truein production;ALLOWED_HOSTSmust be explicit.
Database (SQLAlchemy)
- Always use parameterised queries — never
f"SELECT ... WHERE id={user_id}". - Define models with explicit
__tablename__, column types, and constraints. - Async sessions must be closed; use context managers or
async_scoped_session. - Alembic for migrations; check migration against production schema in CI.
Do not
- Do not use mutable default arguments (
def f(items=[])). - Do not catch bare
Exceptionwithout re-raising or logging with full traceback. - Do not use
picklefor untrusted data deserialization. - Do not import at module level what belongs behind a function scope (avoids circular imports and slow startup).
- Do not store secrets in
settings.py; load from environment and validate at startup.
Common mistakes to avoid
| Mistake | Fix |
|---|---|
| Blocking I/O in an async FastAPI handler | Use await asyncio.to_thread(sync_fn) or an async library. |
| SQLAlchemy lazy load outside session scope | Either expire_on_commit=False, eager-load, or keep the session open. |
Django ORM queries in serialiser to_representation | Move queries to the view with select_related; serialisers must be query-free. |
| Returning Python exceptions as 500 with stack trace | Catch in error handler; return {"detail": "..."} with appropriate status. |
| Tests hitting the production database | Use pytest-django's @pytest.mark.django_db with a test DB, or SQLite in-memory. |
Circular import in FastAPI Depends chain | Restructure deps into a deps.py module imported by both sides. |
Output format
- New endpoint: route function + Pydantic schema + service function, all typed.
- Module layout: directory tree showing
routers/,schemas/,services/,models/,tests/. - Test file:
pytestfunctions covering success, 422 validation error, and 401 auth failure. - Migration: Alembic
upgrade/downgradefunctions with comments on intent.
Related checklists
- .claude/checklists/security.md
- .claude/checklists/performance.md
- .claude/checklists/qa.md
Related agents
- .claude/agents/core/orchestrator.md
- .claude/agents/engineering/devops-engineer.md
What ships with it
Read from the repository
Just SKILL.md. No reference files, no scripts.