python-peewee

narumiruna's avatarfrom narumiruna

Patterns for using Peewee ORM with DatabaseProxy and scoped connections/transactions. Use when setting up DatabaseProxy, managing connection_context/atomic blocks, or writing tests with SQLite.

⭐2stars🔀0forks📁View on GitHub🕐Updated Jan 9, 2026

When & Why to Use This Skill

This Claude skill provides optimized patterns for the Python Peewee ORM, focusing on advanced database management using DatabaseProxy. It streamlines the implementation of scoped connection contexts and atomic transactions, ensuring robust, thread-safe, and efficient database interactions in Python applications.

Use Cases

  • Setting up dynamic database initialization using DatabaseProxy for modular or multi-tenant Python applications.
  • Managing scoped database connections with connection_context to ensure proper opening and closing of resources in web requests.
  • Implementing ACID-compliant operations using atomic transaction blocks to maintain data integrity during complex writes.
  • Creating isolated and reproducible testing environments with SQLite and pytest fixtures for database-driven logic.
namepython-peewee
descriptionPatterns for using Peewee ORM with DatabaseProxy and scoped connections/transactions. Use when setting up DatabaseProxy, managing connection_context/atomic blocks, or writing tests with SQLite.

Python Peewee

Use Peewee with DatabaseProxy and scoped connection/transaction patterns.

Set up

DatabaseProxy & BaseModel

from peewee import DatabaseProxy, Model

db_proxy = DatabaseProxy()

class BaseModel(Model):
    class Meta:
        database = db_proxy

Initialize DB

from peewee import SqliteDatabase

db = SqliteDatabase("app.db", pragmas={"foreign_keys": 1})
db_proxy.initialize(db)

Use connections and transactions

Read (no transaction)

with db_proxy.obj.connection_context():
    rows = MyModel.select().limit(100)

Write (atomic)

with db_proxy.obj.atomic():
    a.save()
    b.save()

Combined

db = db_proxy.obj
with db.connection_context():
    with db.atomic():
        ...

Use connection_context() for scoped connections (open/close). Use atomic() for atomic writes (BEGIN/COMMIT/ROLLBACK).

Test with SQLite

import pytest
from peewee import SqliteDatabase

@pytest.fixture
def test_db(tmp_path):
    db = SqliteDatabase(str(tmp_path / "test.db"))
    db_proxy.initialize(db)
    with db.connection_context():
        db.create_tables([MyModel])
    yield db
    db.close()