惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

阮一峰的网络日志
阮一峰的网络日志
IT之家
IT之家
H
Heimdal Security Blog
Jina AI
Jina AI
宝玉的分享
宝玉的分享
博客园 - 【当耐特】
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
爱范儿
爱范儿
T
Tailwind CSS Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Apple Machine Learning Research
Apple Machine Learning Research
有赞技术团队
有赞技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
AWS News Blog
AWS News Blog
C
Cisco Blogs
Cisco Talos Blog
Cisco Talos Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Hacker News
The Hacker News
The Cloudflare Blog
Hugging Face - Blog
Hugging Face - Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Threatpost
S
Securelist
P
Privacy International News Feed
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
博客园 - 叶小钗
J
Java Code Geeks
V
V2EX
博客园 - Franky
Spread Privacy
Spread Privacy
K
Kaspersky official blog
C
Cyber Attacks, Cyber Crime and Cyber Security
Simon Willison's Weblog
Simon Willison's Weblog
Project Zero
Project Zero
大猫的无限游戏
大猫的无限游戏
S
SegmentFault 最新的问题
C
Cybersecurity and Infrastructure Security Agency CISA
C
CERT Recently Published Vulnerability Notes
Latest news
Latest news
NISL@THU
NISL@THU
罗磊的独立博客
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园_首页
V
Visual Studio Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Enterprise Design Patterns in Python: Repository & Unit of Work — Real-World E-Commerce Example
JEFFERSON ROSAS CHAMBILLA · 2026-06-20 · via DEV Community

JEFFERSON ROSAS CHAMBILLA

Enterprise Design Patterns in Python: Repository & Unit of Work 🐍🏗️

Series: Enterprise Application Architecture | Source: Fowler's EAA Catalog | Code: GitHub Repository


🧠 What Are Enterprise Design Patterns?

Martin Fowler's Patterns of Enterprise Application Architecture (2002) is one of the most influential books in software engineering. It documents recurring architectural solutions — patterns — that solve common problems in enterprise systems: how to organize domain logic, how to talk to databases, how to handle transactions, and more.

In this article, we'll explore two of the most powerful and widely-used patterns from that catalog:

Pattern Category Core Purpose
Repository Data Source Abstracts data access behind a collection-like interface
Unit of Work Data Source Tracks object changes and commits them as a single transaction

These two patterns work beautifully together — and you'll see exactly why with a real-world example.


🛒 The Problem: An E-Commerce Order System

Imagine you're building a backend for an online store. When a customer places an order:

  1. A new Order is created
  2. Each Product's stock is decremented
  3. A Payment record is registered

If any of these steps fail midway, the entire operation should roll back — no partial state. This is exactly the problem the Unit of Work pattern solves, and the Repository pattern makes it all cleanly testable.


📁 Repository Pattern

Definition

"A Repository mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects."
— Martin Fowler, PoEAA

The Repository acts as an in-memory collection of domain objects. Your business logic never knows if it's talking to PostgreSQL, SQLite, or even a mock list — it just calls .add(), .get(), .list().

Domain Model

# models.py
from dataclasses import dataclass, field
from typing import List
from uuid import uuid4

@dataclass
class Product:
    id: str
    name: str
    price: float
    stock: int

@dataclass
class OrderItem:
    product_id: str
    quantity: int
    unit_price: float

@dataclass
class Order:
    id: str = field(default_factory=lambda: str(uuid4()))
    customer_id: str = ""
    items: List[OrderItem] = field(default_factory=list)
    status: str = "pending"

    def add_item(self, product: Product, quantity: int):
        if product.stock < quantity:
            raise ValueError(f"Insufficient stock for {product.name}")
        self.items.append(OrderItem(
            product_id=product.id,
            quantity=quantity,
            unit_price=product.price
        ))

    @property
    def total(self) -> float:
        return sum(item.quantity * item.unit_price for item in self.items)

Abstract Repository Interface

# repositories/base.py
from abc import ABC, abstractmethod
from typing import Generic, List, Optional, TypeVar

T = TypeVar("T")

class AbstractRepository(ABC, Generic[T]):
    @abstractmethod
    def add(self, entity: T) -> None:
        raise NotImplementedError

    @abstractmethod
    def get(self, entity_id: str) -> Optional[T]:
        raise NotImplementedError

    @abstractmethod
    def list(self) -> List[T]:
        raise NotImplementedError

Concrete Implementations

# repositories/order_repository.py
import sqlite3
import json
from typing import List, Optional
from models import Order, OrderItem
from repositories.base import AbstractRepository

class SqliteOrderRepository(AbstractRepository[Order]):
    def __init__(self, connection: sqlite3.Connection):
        self.conn = connection
        self._create_table()

    def _create_table(self):
        self.conn.execute("""
            CREATE TABLE IF NOT EXISTS orders (
                id TEXT PRIMARY KEY,
                customer_id TEXT NOT NULL,
                items TEXT NOT NULL,
                status TEXT NOT NULL
            )
        """)

    def add(self, order: Order) -> None:
        items_json = json.dumps([
            {"product_id": i.product_id, "quantity": i.quantity, "unit_price": i.unit_price}
            for i in order.items
        ])
        self.conn.execute(
            "INSERT INTO orders (id, customer_id, items, status) VALUES (?, ?, ?, ?)",
            (order.id, order.customer_id, items_json, order.status)
        )

    def get(self, order_id: str) -> Optional[Order]:
        cursor = self.conn.execute(
            "SELECT id, customer_id, items, status FROM orders WHERE id = ?",
            (order_id,)
        )
        row = cursor.fetchone()
        if not row:
            return None
        items = [OrderItem(**i) for i in json.loads(row[2])]
        return Order(id=row[0], customer_id=row[1], items=items, status=row[3])

    def list(self) -> List[Order]:
        cursor = self.conn.execute("SELECT id, customer_id, items, status FROM orders")
        orders = []
        for row in cursor.fetchall():
            items = [OrderItem(**i) for i in json.loads(row[2])]
            orders.append(Order(id=row[0], customer_id=row[1], items=items, status=row[3]))
        return orders

# repositories/product_repository.py
import sqlite3
from typing import List, Optional
from models import Product
from repositories.base import AbstractRepository

class SqliteProductRepository(AbstractRepository[Product]):
    def __init__(self, connection: sqlite3.Connection):
        self.conn = connection
        self._create_table()

    def _create_table(self):
        self.conn.execute("""
            CREATE TABLE IF NOT EXISTS products (
                id TEXT PRIMARY KEY,
                name TEXT NOT NULL,
                price REAL NOT NULL,
                stock INTEGER NOT NULL
            )
        """)

    def add(self, product: Product) -> None:
        self.conn.execute(
            "INSERT OR REPLACE INTO products (id, name, price, stock) VALUES (?, ?, ?, ?)",
            (product.id, product.name, product.price, product.stock)
        )

    def get(self, product_id: str) -> Optional[Product]:
        cursor = self.conn.execute(
            "SELECT id, name, price, stock FROM products WHERE id = ?",
            (product_id,)
        )
        row = cursor.fetchone()
        return Product(*row) if row else None

    def list(self) -> List[Product]:
        cursor = self.conn.execute("SELECT id, name, price, stock FROM products")
        return [Product(*row) for row in cursor.fetchall()]

    def update_stock(self, product_id: str, new_stock: int) -> None:
        self.conn.execute(
            "UPDATE products SET stock = ? WHERE id = ?",
            (new_stock, product_id)
        )


🔄 Unit of Work Pattern

Definition

"A Unit of Work maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems."
— Martin Fowler, PoEAA

The UoW ensures that all operations in a business transaction either all succeed or all fail together — like a database transaction, but at the application layer.

Implementation

# unit_of_work.py
import sqlite3
from abc import ABC, abstractmethod
from repositories.order_repository import SqliteOrderRepository
from repositories.product_repository import SqliteProductRepository

class AbstractUnitOfWork(ABC):
    orders: SqliteOrderRepository
    products: SqliteProductRepository

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type:
            self.rollback()
        else:
            self.commit()

    @abstractmethod
    def commit(self):
        raise NotImplementedError

    @abstractmethod
    def rollback(self):
        raise NotImplementedError


class SqliteUnitOfWork(AbstractUnitOfWork):
    def __init__(self, db_path: str = ":memory:"):
        self.db_path = db_path

    def __enter__(self):
        self.conn = sqlite3.connect(self.db_path)
        self.conn.execute("PRAGMA journal_mode=WAL")
        self.orders = SqliteOrderRepository(self.conn)
        self.products = SqliteProductRepository(self.conn)
        return super().__enter__()

    def commit(self):
        self.conn.commit()

    def rollback(self):
        self.conn.rollback()

    def __exit__(self, exc_type, exc_val, exc_tb):
        super().__exit__(exc_type, exc_val, exc_tb)
        self.conn.close()


🚀 Service Layer: Putting It All Together

# services/order_service.py
from typing import List, Tuple
from models import Order
from unit_of_work import AbstractUnitOfWork

class OrderService:

    @staticmethod
    def place_order(
        customer_id: str,
        items: List[Tuple[str, int]],  # [(product_id, quantity), ...]
        uow: AbstractUnitOfWork
    ) -> Order:
        """
        Places an order atomically. All stock updates and order creation
        happen in a single Unit of Work transaction.
        """
        with uow:
            order = Order(customer_id=customer_id)

            for product_id, quantity in items:
                product = uow.products.get(product_id)
                if not product:
                    raise ValueError(f"Product {product_id} not found")

                # This validates stock internally
                order.add_item(product, quantity)

                # Decrement stock
                product.stock -= quantity
                uow.products.update_stock(product.id, product.stock)

            order.status = "confirmed"
            uow.orders.add(order)

            # commit() is called automatically by __exit__
            return order


✅ Testing: The Real Payoff

The biggest benefit of these patterns is testability. We can test all business logic without touching a real database:

# tests/test_order_service.py
import pytest
from models import Product
from services.order_service import OrderService
from unit_of_work import SqliteUnitOfWork

DB_PATH = ":memory:"

@pytest.fixture
def uow():
    return SqliteUnitOfWork(DB_PATH)

def seed_products(uow: SqliteUnitOfWork):
    with uow:
        uow.products.add(Product("p1", "Laptop", 999.99, 10))
        uow.products.add(Product("p2", "Mouse", 29.99, 50))

def test_place_order_success():
    uow = SqliteUnitOfWork(":memory:")
    seed_products(uow)

    order = OrderService.place_order(
        customer_id="customer_001",
        items=[("p1", 2), ("p2", 1)],
        uow=SqliteUnitOfWork(":memory:")  # use fresh UoW in real tests
    )

    assert order.status == "confirmed"
    assert order.total == (2 * 999.99) + 29.99

def test_order_fails_on_insufficient_stock():
    uow = SqliteUnitOfWork(":memory:")
    with pytest.raises(ValueError, match="Insufficient stock"):
        with uow:
            uow.products.add(Product("p3", "GPU", 1200.0, 1))

        OrderService.place_order(
            customer_id="customer_002",
            items=[("p3", 5)],  # Requesting 5, only 1 in stock
            uow=SqliteUnitOfWork(":memory:")
        )


🗂️ Project Structure

enterprise-patterns-python/
│
├── models.py                    # Domain models (Order, Product, OrderItem)
├── unit_of_work.py              # UoW abstract + SQLite implementation
├── repositories/
│   ├── __init__.py
│   ├── base.py                  # AbstractRepository[T]
│   ├── order_repository.py      # SqliteOrderRepository
│   └── product_repository.py    # SqliteProductRepository
├── services/
│   ├── __init__.py
│   └── order_service.py         # OrderService (business logic)
├── tests/
│   └── test_order_service.py    # Pytest tests
├── main.py                      # Demo script
└── requirements.txt


🔑 Key Takeaways

  • Repository Pattern decouples your domain logic from data storage — swap SQLite for PostgreSQL or even a mock list without changing a single line of business code.
  • Unit of Work Pattern coordinates multiple repository operations as a single atomic transaction — no partial state, no data corruption.
  • Together, these patterns produce code that is testable, maintainable, and swappable at the infrastructure layer.
  • This approach is the backbone of Clean Architecture and Domain-Driven Design (DDD) in Python projects.

📚 References & Further Reading


💬 Comment / Peer Review Section

For teammates reviewing this article: Feel free to write your abstract or observation as a comment below! A great starting point:
"This article demonstrates how the Repository pattern enforces a clean boundary between domain logic and persistence. One important observation is that..."


Written by **Jefferson Rosas Chambilla* — Software Engineering student at Universidad Privada de Tacna*