SQLAlchemy extension for FastAPI with support for asynchronous SQLAlchemy sessions and pagination.
Project description
FastAPI-Async-SQLA
FastAPI-Async-SQLA is an SQLAlchemy extension for FastAPI. It supports asynchronous SQLAlchemy sessions using SQLAlchemy >= 2.0 and provides pagination support.
Installing
Using pip:
pip install fastapi-async-sqla
Quick Example
Assuming it runs against a DB with a table user
with 2 columns id
and name
:
# main.py
from fastapi import FastAPI, HTTPException
from fastapi_async_sqla import Base, Item, Page, Paginate, Session, lifespan
from pydantic import BaseModel
from sqlalchemy import select
app = FastAPI(lifespan=lifespan)
class User(Base):
__tablename__ = "user"
class UserIn(BaseModel):
name: str
class UserModel(UserIn):
id: int
@app.get("/users", response_model=Page[UserModel])
async def list_users(paginate: Paginate):
return await paginate(select(User))
@app.get("/users/{user_id}", response_model=Item[UserModel])
async def get_user(user_id: int, session: Session):
user = await session.get(User, user_id)
if user is None:
raise HTTPException(404)
return {"data": user}
@app.post("/users", response_model=Item[UserModel])
async def create_user(new_user: UserIn, session: Session):
user = User(**new_user.model_dump())
session.add(user)
await session.flush()
return {"data": user}
Creating a db using sqlite3
:
sqlite3 db.sqlite <<EOF
CREATE TABLE user (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL
);
EOF
Installing aiosqlite to connect to the sqlite db asynchronously:
pip install aiosqlite
Running the app:
sqlalchemy_url=sqlite+aiosqlite:///db.sqlite?check_same_thread=false uvicorn main:app
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file fastapi_async_sqla-0.2.0.tar.gz
.
File metadata
- Download URL: fastapi_async_sqla-0.2.0.tar.gz
- Upload date:
- Size: 4.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.5
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | c52b390aa2156462a6482fcbefac4a09253209d41d219bd405b4fa4170289f2f |
|
MD5 | d35161415cac6e162917309993695ab9 |
|
BLAKE2b-256 | 89696c19d9365fd0486194725e59259a0709de632328d86e888d86afd0af708d |
Provenance
File details
Details for the file FastAPI_Async_SQLA-0.2.0-py3-none-any.whl
.
File metadata
- Download URL: FastAPI_Async_SQLA-0.2.0-py3-none-any.whl
- Upload date:
- Size: 4.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.5
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | bb13afa4be755ad3ca671955d92ab759e69ee769d7b43bb458061151d48843a4 |
|
MD5 | 774c12bd784ade0b754817f50aa3dcb2 |
|
BLAKE2b-256 | f35875c35abda2d7278362d4f79be441ba9f2b8b6d907276d26f49f4c86871b7 |