pn-python-backend

A set of rules for writing Python server and API code, including applications built with FastAPI or Flask.

In plain words
What is it for?
Use it when building or reviewing Python routes, services, configuration, request handling, and background jobs.
Why use it?
It keeps backend code consistent and helps avoid problems with typing, blocking operations, configuration, secrets, and error handling.

Cursor rule

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/perniemann/pncore/pn-python-backend
Clone the repo
git clone --depth 1 https://github.com/perniemann/pnCore
Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 810 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 1 finding. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.00810
Opus 5 $0.00000 $0.00405
Sonnet 5 $0.00000 $0.00162
Haiku 4.5 $0.00000 $0.00081

Measured yesterday against content hash 4c2251869ecd, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

pn-python-backend scanned grade A with 1 finding against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured yesterday.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Makes network callslowCapability

Not a fault in itself. Listed so you know the mod talks to something, and to what.

- **Blocking in async context**: `requests.get(...)` inside an `async def` route stalls all concurrent requests.
packages/pn-core-mcp/content/rules/pn-python-backend.mdc · 44 lines

How it starts

The opening of the file, as written. The whole thing — 44 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Python / backend rules

Style and typing

  • Type hints on all public functions and class methods — parameters and return type. Use built-in generics (list[str], dict[str, int], X | None) not typing.List, typing.Optional (Python 3.10+).
  • Use pydantic models for all request/response shapes in FastAPI; use dataclasses or pydantic for structured config.
  • Prefer small functions with single responsibility. Classes for stateful services; functions for pure transformations.
  • Use pathlib.Path for file paths. Never string-concatenate paths.
  • Follow PEP 8: snake_case for functions/variables, PascalCase for classes, UPPER_SNAKE for module-level constants.

Async

  • FastAPI routes should be async def when they perform I/O (DB, HTTP, Redis). Use sync only for CPU-bound work.
  • Use asyncio-native libraries in async routes (asyncpg, httpx, motor). Never call blocking I/O (stdlib requests, psycopg2 sync) from an async route handler — it blocks the event loop.
  • For background jobs: use BackgroundTasks (FastAPI) or a task queue (Celery, ARQ, dramatiq); do not fire-and-forget with asyncio.create_task in request scope without error handling.

Secrets and config

  • All config and secrets from environment variables (os.getenv, os.environ). Never hardcode keys or passwords in source.
  • Use pydantic-settings (BaseSettings) for typed, validated config at startup. Validate required vars at import, not lazily.
  • Keep a .env.example; never commit .env to git. Use python-dotenv only in development.

Error handling

  • Catch specific exceptions, not bare except: or broad except Exception:.
  • In FastAPI: raise HTTPException for operational errors; use exception handlers (@app.exception_handler) for centralized formatting.
  • Return consistent JSON error shapes: { "error": { "code": str, "message": str, "requestId": str } }.
  • Use structured logging (structlog or logging with JSON formatter). Include request_id, user_id in log context.

Read the full file on GitHub · 44 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. yesterday First seen · 44 lines · 0 tokens per session scan A 4c2251869ecd

Subscribe to this mod's changes

pn-python-backend is a cursor rule published in the GitHub repository perniemann/pnCore (0 stars, last pushed 2d ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 810 tokens. A static security scan graded it A with 1 finding (makes network calls). No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.