Enterprise Python Project Architecture
Transition from flat 4-file prototypes to modular, enterprise-grade Clean Architecture with explicit layer boundaries.
Why Architectural Boundaries Matter
As applications grow, flat directory structures create tight coupling where database queries, web routes, and business rules bleed into each other. Clean architecture isolates the core domain so that changes to frameworks or databases do not break business logic.
app/
βββ main.py # Entrypoint & HTTP server
βββ models.py # ORM models mixed with rules
βββ routes.py # HTTP routes mixed with SQL
βββ services.py # Monolithic helpers
project/
βββ app/
β βββ api/ # π HTTP Routes & Controllers
β βββ core/ # βοΈ Config, Auth & Logging
β βββ domain/ # π§ Pure Business Entities (No Dependencies)
β βββ application/ # π Use Cases & Workflow Services
β βββ infrastructure/ # π Database, ORM & External APIs
β βββ schemas/ # π Pydantic DTOs & Validation
βββ tests/ # π§ͺ Unit, Integration & E2E Tests
βββ pyproject.toml # π οΈ Dependencies & Package Specs
π Understanding Directory Boundaries & Responsibilities
π api/ (Delivery Layer)
Houses Flask Blueprints or FastAPI routers. Handles HTTP request parsing, JSON serialization, header validation, and status code formatting. Zero SQL or business rules.
βοΈ core/ (Cross-Cutting Concerns)
Houses application configuration (`config.py`), secrets management (`.env`), security utilities (`security.py`), and central JSON loggers (`logging.py`).
π§ domain/ (Pure Business Logic)
The heart of the application. Contains pure Python entities, domain validation rules, and abstract repository contracts. Zero external dependencies.
π application/ (Use Cases & Workflows)
Orchestrates use cases (`RegisterUserUseCase`, `CheckoutOrderUseCase`). Coordinates domain entities, repository contracts, and notification services.
π infrastructure/ (Technical Implementations)
Contains concrete database drivers, SQLAlchemy ORM models, SQL queries, Redis cache clients, and third-party API SDKs (Stripe, SendGrid, AWS S3).
π schemas/ (Data Transfer Objects)
Defines Pydantic models or Python dataclasses used for validating API request bodies and serializing API response payloads.
π― The Core Dependency Rule
The primary goal of enterprise project architecture is not simply memorizing folder namesβit is enforcing the Inward Dependency Rule:
Inner domain entities NEVER import outer layers (Flask, SQLAlchemy, or Requests). If the web framework or database vendor changes, zero lines of domain business logic need to be modified.