Skip to main content

Simplify SQLAlchemy 2.0+ usage.

Project description

SQLAlchemy Toolkit

This project is a library that simplifies the use of SQLAlchemy in Python applications. It also provides a implementation of the repository pattern for SQLAlchemy.

It has a FastAPI integration through a middleware that manages the session and transaction for each request.

PyPI Supported Python versions

Features

Here's what sqlalchemy-repository can do for you. 🚀

  • DatabaseManager: It provides a class that manages the session and transaction for each request.
  • Repository pattern: It provides a implementation of the repository pattern for SQLAlchemy.
  • FastAPI integration: It provides a middleware that manages the session and transaction for each request in FastAPI.
  • Async support: It provides a async version of the DatabaseManager, the Repository pattern and the FastAPI middleware.

Installation

$ pip install sqlalchemy-toolkit
---> 100%
Successfully installed sqlalchemy-toolkit

Usage

Here's a quick example. ✨

A SQL Table

Imagine you have a SQL table called hero with:

  • id
  • name
  • secret_name
  • age

Create a SQLAlchemy model

from typing import Optional

from sqlalchemy import Integer, String
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy_toolkit import Entity


class Hero(Entity):
    __tablename__ = "heroes"

    id: Mapped[Optional[int]] = mapped_column(
        Integer, primary_key=True, nullable=False, autoincrement=True
    )
    name: Mapped[str] = mapped_column(String(255))
    secret_name: Mapped[str] = mapped_column(String(255))
    age: Mapped[Optional[int]] = mapped_column(Integer, nullable=True, default=None)

The class Hero is a SQLAlchemy model. It is a subclass of Entity from sqlalchemy-repository, which is a subclass of SQLAlchemy's DeclarativeBase class.

And each of those class attributes is a SQLAlchemy column.

Create a SQLAlchemy session

from sqlalchemy_toolkit import DatabaseManager

db = DatabaseManager("sqlite:///heroes.db")

The DatabaseManager class is a class that manages the session through the session_ctx method.

Create a repository

from sqlalchemy_toolkit import SQLAlchemyRepository

class HeroRepository(SQLAlchemyRepository[Hero, int]):
    entity_class = Hero

hero_repository = HeroRepository()

Use the repository

with db.session_ctx():
    hero = Hero(name="Deadpond", secret_name="Dive Wilson")

    hero_repository.save(hero)

    heroes = hero_repository.find_all()

FastAPI integration

Here's a quick example using the previous hero model. ✨

Without using the repository

from typing import Any, List, Optional

from fastapi import FastAPI
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy_toolkit import DatabaseManager
from sqlalchemy_toolkit.ext.fastapi import SQLAlchemyMiddleware

from .models import Hero


class HeroDto(BaseModel):
    id: Optional[int]
    name: str
    secret_name: str
    age: int


app = FastAPI()

db = DatabaseManager("sqlite:///heroes.db")

app.add_middleware(SQLAlchemyMiddleware, db=db)


@app.get("/heroes", response_model=List[HeroDto])
def find_all_heroes() -> Any:
    stm = select(Hero)
    return db.session.scalars(stm).all()

Using the repository

from typing import Any, List, Optional

from fastapi import Depends, FastAPI
from pydantic import BaseModel
from sqlalchemy_toolkit import DatabaseManager
from sqlalchemy_toolkit.ext.fastapi import SQLAlchemyMiddleware
from typing_extensions import Annotated

from .repository.hero_repository import HeroRepository


class HeroDto(BaseModel):
    id: Optional[int]
    name: str
    secret_name: str
    age: int


app = FastAPI()

db = DatabaseManager("sqlite:///heroes.db")

app.add_middleware(SQLAlchemyMiddleware, db=db)


@app.get("/heroes", response_model=List[HeroDto])
def find_all_heroes(hero_repository: Annotated[HeroRepository, Depends()]) -> Any:
    return hero_repository.find_all()

License

This project is licensed under the terms of the MIT license.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sqlalchemy_toolkit-0.1.1.tar.gz (5.9 kB view details)

Uploaded Source

Built Distribution

sqlalchemy_toolkit-0.1.1-py3-none-any.whl (7.3 kB view details)

Uploaded Python 3

File details

Details for the file sqlalchemy_toolkit-0.1.1.tar.gz.

File metadata

  • Download URL: sqlalchemy_toolkit-0.1.1.tar.gz
  • Upload date:
  • Size: 5.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.12.4 Linux/6.10.4-200.fc40.x86_64

File hashes

Hashes for sqlalchemy_toolkit-0.1.1.tar.gz
Algorithm Hash digest
SHA256 37111a6c6d64bee91cf2e101e442e30fcb2b0baf0873118f79d82f105b7a89f9
MD5 bf48f07a52509a518a651545c9517f38
BLAKE2b-256 119b2d1785185685ebc47334e17843348b56fb72c565d4c4a308832bf24066e2

See more details on using hashes here.

File details

Details for the file sqlalchemy_toolkit-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: sqlalchemy_toolkit-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 7.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.12.4 Linux/6.10.4-200.fc40.x86_64

File hashes

Hashes for sqlalchemy_toolkit-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e81561b0cdde7b0846b9978d53c8cc43806ef64069acc070dc8876246e5e8a5b
MD5 6ecd1ae32b7afea6689377c7876dd582
BLAKE2b-256 e9022e31b58879b1865962249f3e17827f2306c3ba069b52dda0ac955575bb19

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page