.claude/skills/python-backend-expert/SKILL.md
Python backend expert including Django, FastAPI, Flask, SQLAlchemy, and async patterns
npx skillsauth add oimiragieo/agent-studio python-backend-expertInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
db_default on model fields (e.g., db_default=Now()) instead of Python-side defaults where the database should own the valueModelAdmin.show_facets) to get counts alongside filter optionsasync-native queryset methods — prefer await qs.acount(), await qs.afirst(), async for obj in qs in async viewsMIDDLEWARE list; async-capable middleware is preferred for high-throughput ASGI deploymentsLoginRequiredMiddleware (Django 5.1+) instead of decorating every view when all views require authenticationGeneratedField for database-generated columns (computed from other columns at the DB level)When reviewing or writing code, apply these guidelines:
Use the lifespan context manager (not deprecated @app.on_event) for startup/shutdown resource management:
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
# startup: initialize DB pool, HTTP clients, caches
app.state.db_pool = await create_pool()
yield
# shutdown: close resources
await app.state.db_pool.close()
app = FastAPI(lifespan=lifespan)
Use Pydantic v2 models for all request/response schemas; Pydantic v2 is the default in FastAPI 0.100+. Use model_config = ConfigDict(...) instead of the inner class Config
Use pydantic-settings (BaseSettings) with lru_cache for config management:
from functools import lru_cache
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_url: str
model_config = ConfigDict(env_prefix="APP_")
@lru_cache
def get_settings() -> Settings:
return Settings()
Scope dependencies correctly: per-request (DB sessions, auth), router-level (audit logging, namespace caches), application lifespan (Kafka producers, feature flag SDKs, tracing exporters)
Use Annotated type hints with Depends for cleaner dependency signatures:
from typing import Annotated
from fastapi import Depends
DbSession = Annotated[AsyncSession, Depends(get_db)]
CurrentUser = Annotated[User, Depends(get_current_user)]
Structure projects by domain: routers/, services/, repositories/, schemas/, models/ — avoid flat single-file apps beyond prototypes
Prefer async def path operations for I/O-bound routes; use def (sync) only for CPU-bound work that should run in a thread pool
Use APIRouter with prefix, tags, and dependencies to group related routes and apply shared middleware
When reviewing or writing code, apply these guidelines:
Use create_async_engine + async_sessionmaker (not the deprecated AsyncSession factory directly); create one engine per service at application startup
Use the new Mapped + mapped_column declarative style (SQLAlchemy 2.0+) instead of the legacy Column style:
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy import String
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
email: Mapped[str] = mapped_column(String(255), unique=True)
is_active: Mapped[bool] = mapped_column(default=True)
Provide the DB session via FastAPI dependency injection using async with session scope:
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
async_session = async_sessionmaker(engine, expire_on_commit=False)
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with async_session() as session:
yield session
Use select() (not the legacy session.query()) for all queries in SQLAlchemy 2.0+
Use selectinload / joinedload explicitly to avoid implicit lazy-load I/O in async contexts (lazy loading raises MissingGreenlet in async)
For upserts, use insert().on_conflict_do_update() (PostgreSQL) or the dialect-specific equivalent rather than separate select + update round trips
Use connection pool sizing appropriate for async: async drivers (asyncpg, aiomysql) need smaller pools than sync drivers; pool_size=5, max_overflow=10 is a safe default for moderate load
When reviewing or writing code, apply these guidelines:
python3.13t (free-threaded build). Avoid assuming GIL protection for shared mutable state in new code targeting 3.13+; use explicit locks or thread-safe data structures. Do not enable free-threaded mode in production without thorough testing of all C extensionsPYTHON_JIT=1. Provides measurable speedups for tight loops and numeric code. No code changes needed; just be aware it exists for performance-sensitive servicest"..." string literals that defer interpolation, useful for safe SQL/HTML construction without injection risk. Prefer T-strings over f-strings when building dynamic queries or HTML fragmentsfrom __future__ import annotations needed). This resolves forward-reference issues in type hints at zero runtime costinterpreters stdlib module enables true parallelism via subinterpreters without disabling the GIL. Useful for CPU-bound workloads that previously required multiprocessingpyproject.toml (not setup.py / requirements.txt alone) for all new projects; use uv or pip with pyproject.toml for reproducible dependency managementpyproject.toml requires-python fieldThis expert skill consolidates 1 individual skills:
lifespan context manager for FastAPI startup/shutdown resource management — @app.on_event is deprecated and will be removed in a future release.session.query() in SQLAlchemy 2.0+ — use select() with the 2.0-style API; legacy query API will be removed.async def with awaitable drivers or run_in_executor for blocking operations to avoid event loop starvation.| Anti-Pattern | Why It Fails | Correct Approach |
| ----------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------- |
| Using @app.on_event for startup/shutdown | Deprecated in FastAPI; will break on version upgrade | Use @asynccontextmanager with lifespan parameter |
| Using session.query() in SQLAlchemy 2.0+ | Legacy query API is deprecated and will be removed | Use select() statements with session.execute() |
| Building SQL strings with f-strings or % formatting | SQL injection vulnerability; critical security flaw | Use parameterized queries via ORM or text() with bound params |
| Calling blocking I/O directly in async def routes | Blocks the entire event loop; causes cascading latency | Use awaitable async drivers; loop.run_in_executor() for sync code |
| Putting business logic in FastAPI path functions | Couples routing to logic; makes unit testing impossible | Extract logic to service/repository layer; inject via Depends() |
Before starting:
cat .claude/context/memory/learnings.md
After completing: Record any new patterns or exceptions discovered.
ASSUME INTERRUPTION: Your context may reset. If it's not in memory, it didn't happen.
tools
Comprehensive biosignal processing toolkit for analyzing physiological data including ECG, EEG, EDA, RSP, PPG, EMG, and EOG signals. Use this skill when processing cardiovascular signals, brain activity, electrodermal responses, respiratory patterns, muscle activity, or eye movements. Applicable for heart rate variability analysis, event-related potentials, complexity measures, autonomic nervous system assessment, psychophysiology research, and multi-modal physiological signal integration.
tools
Comprehensive toolkit for creating, analyzing, and visualizing complex networks and graphs in Python. Use when working with network/graph data structures, analyzing relationships between entities, computing graph algorithms (shortest paths, centrality, clustering), detecting communities, generating synthetic networks, or visualizing network topologies. Applicable to social networks, biological networks, transportation systems, citation networks, and any domain involving pairwise relationships.
data-ai
Molecular featurization for ML (100+ featurizers). ECFP, MACCS, descriptors, pretrained models (ChemBERTa), convert SMILES to features, for QSAR and molecular ML.
development
Run Python code in the cloud with serverless containers, GPUs, and autoscaling. Use when deploying ML models, running batch processing jobs, scheduling compute-intensive tasks, or serving APIs that require GPU acceleration or dynamic scaling.