SkilVaultSign inStart free

Catalogue / python-stack-decisions

python-stack-decisions

Older skill: source not recordedSignedGuides Python architecture choices: picking between FastAPI, Django and Flask, deciding async versus sync, planning type hints and project layout, choosing background workers, and shaping error handling and tests. Use when the user says "which framework should I use", "should this be async", "set up…
---
name: python-stack-decisions
description: >-
  Guides Python architecture choices: picking between FastAPI, Django and
  Flask, deciding async versus sync, planning type hints and project layout,
  choosing background workers, and shaping error handling and tests. Use when
  the user says "which framework should I use", "should this be async", "set
  up the project structure", or starts a new Python service or app. Not for
  writing the implementation itself, for data-science notebook work, or for
  language versions and tooling the user has not installed.
---

Python Stack Decision Guide

This is a decision-making skill, not a copy-paste cookbook. The right answer depends on the project in front of you — ask before assuming:

  1. API-only, full-stack, or a script?
  2. Does the user need a built-in admin?
  3. Does the team know async Python?
  4. What infrastructure already exists (databases, queues, deploy target)?

If the framework preference is unclear, ask; do not reach for the same default every time.

1. Framework selection

| Factor | FastAPI | Django | Flask | |---|---|---|---| | Sweet spot | APIs, microservices, ML model serving | Full-stack sites, CMS, admin-heavy apps | Small apps, one-off services, learning | | Async | Native (ASGI) | Since 5.0, partial | Via extensions | | Admin | Build your own | Built-in | Via extensions | | ORM | Bring your own | Django ORM included | Bring your own | | Learning curve | Low | Medium | Low |

Rules of thumb:

  • API-first or serving an ML model → FastAPI (Pydantic validation, ASGI).
  • Content site or admin panel where batteries help → Django.
  • Small, flexible, minimal → Flask.
  • Background workers → a queue library (section 5) beside any framework.

2. Async or sync?

| Choose async when | Choose sync when | |---|---| | Work is I/O-bound (HTTP calls, DB, files) | Work is CPU-bound — use processes instead | | Many concurrent connections | Simple scripts | | Real-time features, websockets | Blocking libraries without async versions | | Team and stack are async-ready | Team is new to async, or the codebase is legacy |

The rule underneath the table: async pays off while *waiting*; CPU work needs multiprocessing or offloading no matter how it is declared. Two ways to lose:

  • Calling blocking libraries inside async def — the whole event loop stalls.
  • Forcing async onto CPU work and calling it parallel.

Async replacements to reach for: httpx (HTTP), asyncpg (PostgreSQL), redis-py's asyncio client, aiofiles (files), SQLAlchemy 2.0 async or Tortoise (ORM). Check the installed versions — async library advice ages fast.

3. Type hints and validation

Annotate always: function parameters, return types, class attributes, public APIs. Let inference handle locals; one-off scripts and most tests can stay loose.

from collections.abc import Callable

def find_account(account_id: int) -> Account | None: ...   # may be absent
def render(payload: str | dict) -> None: ...               # either input
def active_rows() -> list[Row]: ...                        # typed collection
def index_map() -> dict[str, int]: ...
def transform(fn: Callable[[int], str]) -> str: ...        # injected function

Reach for Pydantic when data crosses a boundary: request/response models, settings and configuration, input validation, serialization. You get runtime validation, JSON Schema generation, and (with FastAPI) native integration. Type hints alone never validate runtime data — Pydantic does.

4. Project layout

| Scale | Shape | |---|---| | Script | main.py, utils.py, requirements.txt | | Medium API | app/ with models/, routes/, services/, schemas/, plus tests/ and pyproject.toml | | Large app | src/myapp/ with core/, api/, services/, models/, plus tests and packaging metadata |

Inside FastAPI apps, organize either by layer (routes/, services/, models/, schemas/, dependencies/) or by feature (users/ containing its own routes, service, schemas). Either is fine — pick per cohesion and keep business rules out of the route handlers.

Django specifics

  • Fat models, thin views; custom managers for repeated queries; abstract base

classes for shared fields.

  • Class-based views for complex CRUD, function views for simple endpoints,

DRF viewsets where a plain REST API fits.

  • Fight N+1: select_related for foreign keys, prefetch_related for

many-to-many, .only() when you truly need fewer fields.

  • Async in Django (5.0+): async views and middleware, limited async ORM, ASGI

deployment. Worth it for external API calls, Channels websockets, and high-concurrency views — check the installed version's limits first.

FastAPI specifics

async def when the handlers await async drivers or HTTP calls; plain def for blocking or CPU work — FastAPI runs those in a threadpool automatically. Use dependencies for sessions, current user, configuration, and shared resources: they mock cleanly in tests and support yield-based cleanup.

@app.post("/invoices")
async def create_invoice(invoice: InvoiceCreate) -> InvoiceResponse:
    ...  # invoice already validated by Pydantic; response shaped by the annotation

5. Background work

| Option | Best for | |---|---| | FastAPI BackgroundTasks | Quick fire-and-forget in the same process | | Celery | Distributed workers, complex workflows, retries | | ARQ | Async, Redis-based queues | | RQ | Simple Redis queue | | Dramatiq | Actor-based, lighter than Celery |

In-process BackgroundTasks die with the process — acceptable only when losing the job is acceptable. Anything long-running, retryable, or durable belongs on a real queue with persistent storage.

6. Errors and testing

Error strategy: raise domain exceptions in services, catch and transform them in registered handlers, and return one consistent shape — machine-readable code, human-readable message, field-level details where relevant. Never leak stack traces or internals to clients.

| Test layer | Purpose | Tools | |---|---|---| | Unit | Business logic | pytest | | Integration | API endpoints | pytest + httpx/TestClient | | End-to-end | Full workflows | pytest + real database |

@pytest.mark.asyncio
async def test_list_invoices():
    transport = httpx.ASGITransport(app=app)   # current httpx pattern
    async with httpx.AsyncClient(transport=transport, base_url="http://test") as c:
        r = await c.get("/invoices")
        assert r.status_code == 200

Standard fixtures to provide: a database session, a test client, an authenticated user, and sample data. Verify the transport setup against the installed httpx version rather than older AsyncClient(app=...) snippets.

7. Pre-implementation checklist

  • [ ] Framework chosen for *this* context, preference asked
  • [ ] Async-vs-sync decided per workload, not per fashion
  • [ ] Type-hint strategy set (public APIs annotated, Pydantic at boundaries)
  • [ ] Layout picked and business logic placed outside handlers
  • [ ] Error shape defined; background tasks given a durability decision
  • [ ] Critical paths covered by tests

Common traps: defaulting to Django for a simple API, sync calls inside async code, untyped public APIs, business logic in routes, ignored N+1 queries, and mixing sync/async casually. Do the opposites.

---

This skill only advises; nothing is written, installed, or executed unless you ask.

Never

  • Call blocking libraries inside async def and assume it still concurrent.
  • Ship a framework default without checking it fits the project's context.
  • Expose stack traces or internal error detail in client responses.
  • Treat fire-and-forget background tasks as durable job processing.
  • Quote async-library recommendations without verifying the installed versions.