fastapi-async-db-plugin 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fastapi_async_db_plugin-0.1.0/LICENSE +21 -0
- fastapi_async_db_plugin-0.1.0/PKG-INFO +70 -0
- fastapi_async_db_plugin-0.1.0/README.md +48 -0
- fastapi_async_db_plugin-0.1.0/pyproject.toml +31 -0
- fastapi_async_db_plugin-0.1.0/setup.cfg +4 -0
- fastapi_async_db_plugin-0.1.0/src/fastapi_async_db_plugin.egg-info/PKG-INFO +70 -0
- fastapi_async_db_plugin-0.1.0/src/fastapi_async_db_plugin.egg-info/SOURCES.txt +12 -0
- fastapi_async_db_plugin-0.1.0/src/fastapi_async_db_plugin.egg-info/dependency_links.txt +1 -0
- fastapi_async_db_plugin-0.1.0/src/fastapi_async_db_plugin.egg-info/requires.txt +5 -0
- fastapi_async_db_plugin-0.1.0/src/fastapi_async_db_plugin.egg-info/top_level.txt +1 -0
- fastapi_async_db_plugin-0.1.0/src/fastapi_db_plugin/__init__.py +9 -0
- fastapi_async_db_plugin-0.1.0/src/fastapi_db_plugin/config.py +18 -0
- fastapi_async_db_plugin-0.1.0/src/fastapi_db_plugin/models_example.py +14 -0
- fastapi_async_db_plugin-0.1.0/src/fastapi_db_plugin/session.py +93 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Your Name
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fastapi-async-db-plugin
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A production-grade async SQLAlchemy database plugin for FastAPI.
|
|
5
|
+
Author-email: vaibhav734 <vaibhav734@users.noreply.github.com>
|
|
6
|
+
Project-URL: Homepage, https://github.com/vaibhav734/astapi-async-db-plugin
|
|
7
|
+
Project-URL: Bug Tracker, https://github.com/vaibhav734/astapi-async-db-plugin/issues
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Framework :: FastAPI
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Topic :: Database
|
|
13
|
+
Requires-Python: >=3.11
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: fastapi>=0.100.0
|
|
17
|
+
Requires-Dist: sqlalchemy[asyncio]>=2.0.0
|
|
18
|
+
Requires-Dist: asyncpg>=0.28.0
|
|
19
|
+
Requires-Dist: pydantic>=2.0.0
|
|
20
|
+
Requires-Dist: pydantic-settings>=2.0.0
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# FastAPI Async DB Plugin
|
|
24
|
+
|
|
25
|
+
A reusable, boilerplate-free async database plugin for FastAPI using SQLAlchemy 2.0 and asyncpg.
|
|
26
|
+
|
|
27
|
+
## Installation
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install fastapi-async-db-plugin
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Setup & Usage
|
|
34
|
+
|
|
35
|
+
Simply import the plugin functions into your FastAPI app and provide a `.env` file with `DATABASE_URL`:
|
|
36
|
+
|
|
37
|
+
```env
|
|
38
|
+
DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/dbname
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### Example `main.py`
|
|
42
|
+
```python
|
|
43
|
+
from fastapi import FastAPI, Depends, HTTPException
|
|
44
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
45
|
+
from sqlalchemy import select
|
|
46
|
+
|
|
47
|
+
from fastapi_db_plugin import get_db_session, register_db_events
|
|
48
|
+
from fastapi_db_plugin.models_example import User
|
|
49
|
+
|
|
50
|
+
app = FastAPI(title="Reusable DB App Example")
|
|
51
|
+
|
|
52
|
+
# Automatically wire up connection pools and dispose them on shutdown.
|
|
53
|
+
register_db_events(app, create_all=True)
|
|
54
|
+
|
|
55
|
+
@app.post("/users/")
|
|
56
|
+
async def create_user(username: str, email: str, db: AsyncSession = Depends(get_db_session)):
|
|
57
|
+
new_user = User(username=username, email=email)
|
|
58
|
+
db.add(new_user)
|
|
59
|
+
|
|
60
|
+
await db.commit()
|
|
61
|
+
await db.refresh(new_user)
|
|
62
|
+
|
|
63
|
+
return {"id": new_user.id, "username": new_user.username, "email": new_user.email}
|
|
64
|
+
|
|
65
|
+
@app.get("/users/")
|
|
66
|
+
async def list_users(db: AsyncSession = Depends(get_db_session)):
|
|
67
|
+
result = await db.execute(select(User))
|
|
68
|
+
users = result.scalars().all()
|
|
69
|
+
return [{"id": u.id, "username": u.username, "email": u.email} for u in users]
|
|
70
|
+
```
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# FastAPI Async DB Plugin
|
|
2
|
+
|
|
3
|
+
A reusable, boilerplate-free async database plugin for FastAPI using SQLAlchemy 2.0 and asyncpg.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install fastapi-async-db-plugin
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Setup & Usage
|
|
12
|
+
|
|
13
|
+
Simply import the plugin functions into your FastAPI app and provide a `.env` file with `DATABASE_URL`:
|
|
14
|
+
|
|
15
|
+
```env
|
|
16
|
+
DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/dbname
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
### Example `main.py`
|
|
20
|
+
```python
|
|
21
|
+
from fastapi import FastAPI, Depends, HTTPException
|
|
22
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
23
|
+
from sqlalchemy import select
|
|
24
|
+
|
|
25
|
+
from fastapi_db_plugin import get_db_session, register_db_events
|
|
26
|
+
from fastapi_db_plugin.models_example import User
|
|
27
|
+
|
|
28
|
+
app = FastAPI(title="Reusable DB App Example")
|
|
29
|
+
|
|
30
|
+
# Automatically wire up connection pools and dispose them on shutdown.
|
|
31
|
+
register_db_events(app, create_all=True)
|
|
32
|
+
|
|
33
|
+
@app.post("/users/")
|
|
34
|
+
async def create_user(username: str, email: str, db: AsyncSession = Depends(get_db_session)):
|
|
35
|
+
new_user = User(username=username, email=email)
|
|
36
|
+
db.add(new_user)
|
|
37
|
+
|
|
38
|
+
await db.commit()
|
|
39
|
+
await db.refresh(new_user)
|
|
40
|
+
|
|
41
|
+
return {"id": new_user.id, "username": new_user.username, "email": new_user.email}
|
|
42
|
+
|
|
43
|
+
@app.get("/users/")
|
|
44
|
+
async def list_users(db: AsyncSession = Depends(get_db_session)):
|
|
45
|
+
result = await db.execute(select(User))
|
|
46
|
+
users = result.scalars().all()
|
|
47
|
+
return [{"id": u.id, "username": u.username, "email": u.email} for u in users]
|
|
48
|
+
```
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "fastapi-async-db-plugin"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
authors = [
|
|
9
|
+
{ name="vaibhav734", email="vaibhav734@users.noreply.github.com" },
|
|
10
|
+
]
|
|
11
|
+
description = "A production-grade async SQLAlchemy database plugin for FastAPI."
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
requires-python = ">=3.11"
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Framework :: FastAPI",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Topic :: Database",
|
|
20
|
+
]
|
|
21
|
+
dependencies = [
|
|
22
|
+
"fastapi>=0.100.0",
|
|
23
|
+
"sqlalchemy[asyncio]>=2.0.0",
|
|
24
|
+
"asyncpg>=0.28.0",
|
|
25
|
+
"pydantic>=2.0.0",
|
|
26
|
+
"pydantic-settings>=2.0.0"
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Homepage = "https://github.com/vaibhav734/astapi-async-db-plugin"
|
|
31
|
+
"Bug Tracker" = "https://github.com/vaibhav734/astapi-async-db-plugin/issues"
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fastapi-async-db-plugin
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A production-grade async SQLAlchemy database plugin for FastAPI.
|
|
5
|
+
Author-email: vaibhav734 <vaibhav734@users.noreply.github.com>
|
|
6
|
+
Project-URL: Homepage, https://github.com/vaibhav734/astapi-async-db-plugin
|
|
7
|
+
Project-URL: Bug Tracker, https://github.com/vaibhav734/astapi-async-db-plugin/issues
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Framework :: FastAPI
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Topic :: Database
|
|
13
|
+
Requires-Python: >=3.11
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: fastapi>=0.100.0
|
|
17
|
+
Requires-Dist: sqlalchemy[asyncio]>=2.0.0
|
|
18
|
+
Requires-Dist: asyncpg>=0.28.0
|
|
19
|
+
Requires-Dist: pydantic>=2.0.0
|
|
20
|
+
Requires-Dist: pydantic-settings>=2.0.0
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# FastAPI Async DB Plugin
|
|
24
|
+
|
|
25
|
+
A reusable, boilerplate-free async database plugin for FastAPI using SQLAlchemy 2.0 and asyncpg.
|
|
26
|
+
|
|
27
|
+
## Installation
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install fastapi-async-db-plugin
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Setup & Usage
|
|
34
|
+
|
|
35
|
+
Simply import the plugin functions into your FastAPI app and provide a `.env` file with `DATABASE_URL`:
|
|
36
|
+
|
|
37
|
+
```env
|
|
38
|
+
DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/dbname
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### Example `main.py`
|
|
42
|
+
```python
|
|
43
|
+
from fastapi import FastAPI, Depends, HTTPException
|
|
44
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
45
|
+
from sqlalchemy import select
|
|
46
|
+
|
|
47
|
+
from fastapi_db_plugin import get_db_session, register_db_events
|
|
48
|
+
from fastapi_db_plugin.models_example import User
|
|
49
|
+
|
|
50
|
+
app = FastAPI(title="Reusable DB App Example")
|
|
51
|
+
|
|
52
|
+
# Automatically wire up connection pools and dispose them on shutdown.
|
|
53
|
+
register_db_events(app, create_all=True)
|
|
54
|
+
|
|
55
|
+
@app.post("/users/")
|
|
56
|
+
async def create_user(username: str, email: str, db: AsyncSession = Depends(get_db_session)):
|
|
57
|
+
new_user = User(username=username, email=email)
|
|
58
|
+
db.add(new_user)
|
|
59
|
+
|
|
60
|
+
await db.commit()
|
|
61
|
+
await db.refresh(new_user)
|
|
62
|
+
|
|
63
|
+
return {"id": new_user.id, "username": new_user.username, "email": new_user.email}
|
|
64
|
+
|
|
65
|
+
@app.get("/users/")
|
|
66
|
+
async def list_users(db: AsyncSession = Depends(get_db_session)):
|
|
67
|
+
result = await db.execute(select(User))
|
|
68
|
+
users = result.scalars().all()
|
|
69
|
+
return [{"id": u.id, "username": u.username, "email": u.email} for u in users]
|
|
70
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/fastapi_async_db_plugin.egg-info/PKG-INFO
|
|
5
|
+
src/fastapi_async_db_plugin.egg-info/SOURCES.txt
|
|
6
|
+
src/fastapi_async_db_plugin.egg-info/dependency_links.txt
|
|
7
|
+
src/fastapi_async_db_plugin.egg-info/requires.txt
|
|
8
|
+
src/fastapi_async_db_plugin.egg-info/top_level.txt
|
|
9
|
+
src/fastapi_db_plugin/__init__.py
|
|
10
|
+
src/fastapi_db_plugin/config.py
|
|
11
|
+
src/fastapi_db_plugin/models_example.py
|
|
12
|
+
src/fastapi_db_plugin/session.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
fastapi_db_plugin
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
2
|
+
|
|
3
|
+
class DatabaseSettings(BaseSettings):
|
|
4
|
+
# E.g., postgresql+asyncpg://user:password@localhost:5432/dbname
|
|
5
|
+
DATABASE_URL: str
|
|
6
|
+
|
|
7
|
+
# SQLAlchemy engine pool parameters
|
|
8
|
+
pool_size: int = 5
|
|
9
|
+
max_overflow: int = 10
|
|
10
|
+
pool_recycle: int = 3600
|
|
11
|
+
pool_pre_ping: bool = True
|
|
12
|
+
echo: bool = False
|
|
13
|
+
|
|
14
|
+
model_config = SettingsConfigDict(
|
|
15
|
+
env_file=".env",
|
|
16
|
+
env_file_encoding="utf-8",
|
|
17
|
+
extra="ignore"
|
|
18
|
+
)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from sqlalchemy import String
|
|
2
|
+
from sqlalchemy.orm import Mapped, mapped_column
|
|
3
|
+
|
|
4
|
+
from .session import Base
|
|
5
|
+
|
|
6
|
+
class User(Base):
|
|
7
|
+
__tablename__ = "users"
|
|
8
|
+
|
|
9
|
+
id: Mapped[int] = mapped_column(primary_key=True, index=True, autoincrement=True)
|
|
10
|
+
username: Mapped[str] = mapped_column(String(50), unique=True, index=True, nullable=False)
|
|
11
|
+
email: Mapped[str] = mapped_column(String(255), unique=True, index=True, nullable=False)
|
|
12
|
+
|
|
13
|
+
def __repr__(self) -> str:
|
|
14
|
+
return f"<User(id={self.id}, username='{self.username}', email='{self.email}')>"
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import AsyncGenerator
|
|
3
|
+
|
|
4
|
+
from fastapi import FastAPI
|
|
5
|
+
from sqlalchemy.ext.asyncio import (
|
|
6
|
+
AsyncEngine,
|
|
7
|
+
AsyncSession,
|
|
8
|
+
async_sessionmaker,
|
|
9
|
+
create_async_engine,
|
|
10
|
+
)
|
|
11
|
+
from sqlalchemy.orm import declarative_base
|
|
12
|
+
|
|
13
|
+
from .config import DatabaseSettings
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
Base = declarative_base()
|
|
18
|
+
|
|
19
|
+
class DatabaseManager:
|
|
20
|
+
def __init__(self) -> None:
|
|
21
|
+
self.engine: AsyncEngine | None = None
|
|
22
|
+
self.session_factory: async_sessionmaker[AsyncSession] | None = None
|
|
23
|
+
|
|
24
|
+
def init_db(self, settings: DatabaseSettings) -> None:
|
|
25
|
+
"""Initialize the global async engine and session factory."""
|
|
26
|
+
if self.engine is None:
|
|
27
|
+
self.engine = create_async_engine(
|
|
28
|
+
settings.DATABASE_URL,
|
|
29
|
+
pool_size=settings.pool_size,
|
|
30
|
+
max_overflow=settings.max_overflow,
|
|
31
|
+
pool_recycle=settings.pool_recycle,
|
|
32
|
+
pool_pre_ping=settings.pool_pre_ping,
|
|
33
|
+
echo=settings.echo,
|
|
34
|
+
)
|
|
35
|
+
self.session_factory = async_sessionmaker(
|
|
36
|
+
bind=self.engine,
|
|
37
|
+
class_=AsyncSession,
|
|
38
|
+
expire_on_commit=False,
|
|
39
|
+
autoflush=False,
|
|
40
|
+
autocommit=False,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
async def close_db(self) -> None:
|
|
44
|
+
"""Dispose of the global async engine."""
|
|
45
|
+
if self.engine is not None:
|
|
46
|
+
await self.engine.dispose()
|
|
47
|
+
self.engine = None
|
|
48
|
+
self.session_factory = None
|
|
49
|
+
|
|
50
|
+
# Global instance holding the engine state
|
|
51
|
+
db_manager = DatabaseManager()
|
|
52
|
+
|
|
53
|
+
async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
|
|
54
|
+
"""
|
|
55
|
+
FastAPI dependency that provides a safe per-request database session.
|
|
56
|
+
Automatically rolls back transactions if an exception occurs routing.
|
|
57
|
+
"""
|
|
58
|
+
if db_manager.session_factory is None:
|
|
59
|
+
raise RuntimeError("Database is not initialized. Call register_db_events(app) on startup.")
|
|
60
|
+
|
|
61
|
+
async with db_manager.session_factory() as session:
|
|
62
|
+
try:
|
|
63
|
+
yield session
|
|
64
|
+
except Exception:
|
|
65
|
+
await session.rollback()
|
|
66
|
+
raise
|
|
67
|
+
finally:
|
|
68
|
+
await session.close()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def register_db_events(app: FastAPI, create_all: bool = False) -> None:
|
|
72
|
+
"""
|
|
73
|
+
Register startup and shutdown events for the database lifecycle.
|
|
74
|
+
Attaches engine initialization and teardown securely to the app.
|
|
75
|
+
"""
|
|
76
|
+
settings = DatabaseSettings()
|
|
77
|
+
|
|
78
|
+
@app.on_event("startup")
|
|
79
|
+
async def on_startup() -> None:
|
|
80
|
+
logger.info("Initializing database connection...")
|
|
81
|
+
db_manager.init_db(settings)
|
|
82
|
+
|
|
83
|
+
if create_all:
|
|
84
|
+
if db_manager.engine is None:
|
|
85
|
+
raise RuntimeError("Engine initialization failed.")
|
|
86
|
+
logger.info("Creating database tables...")
|
|
87
|
+
async with db_manager.engine.begin() as conn:
|
|
88
|
+
await conn.run_sync(Base.metadata.create_all)
|
|
89
|
+
|
|
90
|
+
@app.on_event("shutdown")
|
|
91
|
+
async def on_shutdown() -> None:
|
|
92
|
+
logger.info("Closing database connection...")
|
|
93
|
+
await db_manager.close_db()
|