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.
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:
idnamesecret_nameage
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.
Metadata
Release files for sqlalchemy-toolkit 0.1.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| sqlalchemy_toolkit-0.1.1.tar.gz | 5.9 kB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| sqlalchemy_toolkit-0.1.1-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 13.2 kB
Release files / sqlalchemy_toolkit-0.1.1.tar.gz
| Download URL | sqlalchemy_toolkit-0.1.1.tar.gz |
|---|---|
| Size | 5.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
37111a6c6d64bee91cf2e101e442e30fcb2b0baf0873118f79d82f105b7a89f9
|
|
BLAKE2b-256 checksum How to use checksums |
119b2d1785185685ebc47334e17843348b56fb72c565d4c4a308832bf24066e2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/1.8.3 CPython/3.12.4 Linux/6.10.4-200.fc40.x86_64
|
Release files / sqlalchemy_toolkit-0.1.1-py3-none-any.whl
| Download URL | sqlalchemy_toolkit-0.1.1-py3-none-any.whl |
|---|---|
| Size | 7.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e81561b0cdde7b0846b9978d53c8cc43806ef64069acc070dc8876246e5e8a5b
|
|
BLAKE2b-256 checksum How to use checksums |
e9022e31b58879b1865962249f3e17827f2306c3ba069b52dda0ac955575bb19
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/1.8.3 CPython/3.12.4 Linux/6.10.4-200.fc40.x86_64
|
Security for sqlalchemy-toolkit 0.1.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.