# 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](https://img.shields.io/pypi/v/sqlalchemy-toolkit.svg)
![Supported Python versions](https://img.shields.io/pypi/pyversions/sqlalchemy-toolkit.svg)
## 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
```console
$ 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
```python
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
```python
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
```python
from sqlalchemy_toolkit import SQLAlchemyRepository
class HeroRepository(SQLAlchemyRepository[Hero, int]):
entity_class = Hero
hero_repository = HeroRepository()
```
### Use the repository
```python
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
```python
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
```python
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](https://github.com/javalce/sqlalchemy-toolkit/blob/master/LICENSE).
Raw data
{
"_id": null,
"home_page": "https://github.com/javalce/sqlalchemy-toolkit",
"name": "sqlalchemy-toolkit",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.8",
"maintainer_email": null,
"keywords": "sqlalchemy",
"author": "Javier Valero Cejudo",
"author_email": "javalce29@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/ec/f8/dfdc64b1898e66c4f8b681ef337f4006f9fc079846c0a0f63c5d63a083b7/sqlalchemy_toolkit-0.1.0.tar.gz",
"platform": null,
"description": "# SQLAlchemy Toolkit\n\nThis project is a library that simplifies the use of SQLAlchemy in Python applications. It also provides a implementation of the repository pattern for SQLAlchemy.\n\nIt has a FastAPI integration through a middleware that manages the session and transaction for each request.\n\n![PyPI](https://img.shields.io/pypi/v/sqlalchemy-toolkit.svg)\n![Supported Python versions](https://img.shields.io/pypi/pyversions/sqlalchemy-toolkit.svg)\n\n## Features\n\nHere's what sqlalchemy-repository can do for you. \ud83d\ude80\n\n- **DatabaseManager**: It provides a class that manages the session and transaction for each request.\n- **Repository pattern**: It provides a implementation of the repository pattern for SQLAlchemy.\n- **FastAPI integration**: It provides a middleware that manages the session and transaction for each request in FastAPI.\n- **Async support**: It provides a async version of the DatabaseManager, the Repository pattern and the FastAPI middleware.\n\n## Installation\n\n```console\n$ pip install sqlalchemy-toolkit\n---> 100%\nSuccessfully installed sqlalchemy-toolkit\n```\n\n## Usage\n\nHere's a quick example. \u2728\n\n### A SQL Table\n\nImagine you have a SQL table called `hero` with:\n\n- `id`\n- `name`\n- `secret_name`\n- `age`\n\n### Create a SQLAlchemy model\n\n```python\nfrom typing import Optional\n\nfrom sqlalchemy import Integer, String\nfrom sqlalchemy.orm import Mapped, mapped_column\nfrom sqlalchemy_toolkit import Entity\n\n\nclass Hero(Entity):\n __tablename__ = \"heroes\"\n\n id: Mapped[Optional[int]] = mapped_column(\n Integer, primary_key=True, nullable=False, autoincrement=True\n )\n name: Mapped[str] = mapped_column(String(255))\n secret_name: Mapped[str] = mapped_column(String(255))\n age: Mapped[Optional[int]] = mapped_column(Integer, nullable=True, default=None)\n```\n\nThe class `Hero` is a **SQLAlchemy** model. It is a subclass of `Entity` from **sqlalchemy-repository**, which is a subclass of `SQLAlchemy`'s `DeclarativeBase` class.\n\nAnd each of those class attributes is a **SQLAlchemy** column.\n\n### Create a SQLAlchemy session\n\n```python\nfrom sqlalchemy_toolkit import DatabaseManager\n\ndb = DatabaseManager(\"sqlite:///heroes.db\")\n```\n\nThe `DatabaseManager` class is a class that manages the session through the `session_ctx` method.\n\n### Create a repository\n\n```python\nfrom sqlalchemy_toolkit import SQLAlchemyRepository\n\nclass HeroRepository(SQLAlchemyRepository[Hero, int]):\n entity_class = Hero\n\nhero_repository = HeroRepository()\n```\n\n### Use the repository\n\n```python\nwith db.session_ctx():\n hero = Hero(name=\"Deadpond\", secret_name=\"Dive Wilson\")\n\n hero_repository.save(hero)\n\n heroes = hero_repository.find_all()\n```\n\n## FastAPI integration\n\nHere's a quick example using the previous hero model. \u2728\n\n### Without using the repository\n\n```python\nfrom typing import Any, List, Optional\n\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\nfrom sqlalchemy import select\nfrom sqlalchemy_toolkit import DatabaseManager\nfrom sqlalchemy_toolkit.ext.fastapi import SQLAlchemyMiddleware\n\nfrom .models import Hero\n\n\nclass HeroDto(BaseModel):\n id: Optional[int]\n name: str\n secret_name: str\n age: int\n\n\napp = FastAPI()\n\ndb = DatabaseManager(\"sqlite:///heroes.db\")\n\napp.add_middleware(SQLAlchemyMiddleware, db=db)\n\n\n@app.get(\"/heroes\", response_model=List[HeroDto])\ndef find_all_heroes() -> Any:\n stm = select(Hero)\n return db.session.scalars(stm).all()\n```\n\n### Using the repository\n\n```python\nfrom typing import Any, List, Optional\n\nfrom fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\nfrom sqlalchemy_toolkit import DatabaseManager\nfrom sqlalchemy_toolkit.ext.fastapi import SQLAlchemyMiddleware\nfrom typing_extensions import Annotated\n\nfrom .repository.hero_repository import HeroRepository\n\n\nclass HeroDto(BaseModel):\n id: Optional[int]\n name: str\n secret_name: str\n age: int\n\n\napp = FastAPI()\n\ndb = DatabaseManager(\"sqlite:///heroes.db\")\n\napp.add_middleware(SQLAlchemyMiddleware, db=db)\n\n\n@app.get(\"/heroes\", response_model=List[HeroDto])\ndef find_all_heroes(hero_repository: Annotated[HeroRepository, Depends()]) -> Any:\n return hero_repository.find_all()\n```\n\n## License\n\nThis project is licensed under the terms of the [MIT license](https://github.com/javalce/sqlalchemy-toolkit/blob/master/LICENSE).\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Simplify SQLAlchemy 2.0+ usage.",
"version": "0.1.0",
"project_urls": {
"Homepage": "https://github.com/javalce/sqlalchemy-toolkit",
"Repository": "https://github.com/javalce/sqlalchemy-toolkit"
},
"split_keywords": [
"sqlalchemy"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "17927b525cfc6ceef1cda31c4857d1163d28a685cb555b5514466b68b2d8c656",
"md5": "f6d3b5a42c16568ecb7cbc7c6bc2d045",
"sha256": "0d220badc6695a7ce3f2c077ef1f421c067a7ca5dfd36ab4379a48bf021c8613"
},
"downloads": -1,
"filename": "sqlalchemy_toolkit-0.1.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "f6d3b5a42c16568ecb7cbc7c6bc2d045",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.8",
"size": 7176,
"upload_time": "2024-04-05T12:15:25",
"upload_time_iso_8601": "2024-04-05T12:15:25.829601Z",
"url": "https://files.pythonhosted.org/packages/17/92/7b525cfc6ceef1cda31c4857d1163d28a685cb555b5514466b68b2d8c656/sqlalchemy_toolkit-0.1.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "ecf8dfdc64b1898e66c4f8b681ef337f4006f9fc079846c0a0f63c5d63a083b7",
"md5": "dc033c3fc8bf35d477a3a674f79253ed",
"sha256": "5adc5938103e7db2751163f8f22572e4438c809862432822c2a86c3f7d730cf6"
},
"downloads": -1,
"filename": "sqlalchemy_toolkit-0.1.0.tar.gz",
"has_sig": false,
"md5_digest": "dc033c3fc8bf35d477a3a674f79253ed",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.8",
"size": 5815,
"upload_time": "2024-04-05T12:15:28",
"upload_time_iso_8601": "2024-04-05T12:15:28.281658Z",
"url": "https://files.pythonhosted.org/packages/ec/f8/dfdc64b1898e66c4f8b681ef337f4006f9fc079846c0a0f63c5d63a083b7/sqlalchemy_toolkit-0.1.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-04-05 12:15:28",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "javalce",
"github_project": "sqlalchemy-toolkit",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "sqlalchemy-toolkit"
}