fastapi-sa provides a simple integration between FastAPI and SQLAlchemy in your application
Project description
fastapi-sa
fastapi-sa provides a simple integration between FastAPI and SQLAlchemy in your application. you can use decorators or middleware to transaction management.
Installing
install and update using pip:
pip install fastapi-sa
Examples
Create models for examples, models.py
from pydantic import BaseModel
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import declarative_base
Base = declarative_base()
class User(Base):
"""UserModel"""
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String(255))
age = Column(Integer)
class UserSchema(BaseModel):
"""user schema"""
id: int
name: str
age: int
class Config:
"""config"""
orm_mode = True
Database migrations for examples
code for create tables, also you can use database migrations.
from sqlalchemy import create_engine
from models import Base
engine = create_engine('sqlite+aiosqlite:////tmp/test.db')
Base.metadata.create_all(engine)
DB init for examples
from fastapi_sa.database import db
db.init(url='sqlite+aiosqlite:////tmp/test.db')
Usage 1: fastapi middleware
from fastapi import FastAPI
from sqlalchemy import select
from fastapi_sa.database import db
from fastapi_sa.middleware import DBSessionMiddleware
from tests.example.db import User, UserSchema
app = FastAPI()
app.add_middleware(DBSessionMiddleware)
@app.get('/users')
async def get_users():
"""get all users"""
result = await db.session.scalars(select(User))
objs = [UserSchema.from_orm(i) for i in result.all()]
return objs
Usage 2: other asynchronous database operations
from sqlalchemy import select
from fastapi_sa.database import db, session_ctx
from tests.example.db import User, UserSchema
@session_ctx
async def get_users():
"""get users"""
results = await db.session.scalars(select(User))
objs = [UserSchema.from_orm(i) for i in results.all()]
return objs
Usage 3: with fixtures in pytest
import pytest
from fastapi_sa.database import db
@pytest.fixture()
def db_session_ctx():
"""db session context"""
token = db.set_session_ctx()
yield
db.reset_session_ctx(token)
@pytest.fixture()
async def session(db_session_ctx):
"""session fixture"""
async with db.session.begin():
yield db.session
If you initialize data in fixture, please use
from fastapi_sa.database import db
from models import User
async with db():
users = User(name='aoo', age=12)
db.session.add(users)
await db.session.flush()
if you test class methods, please use
import pytest
from sqlalchemy import func, select
from models import User, UserSchema
from fastapi_sa.database import db
class UserRepository:
"""user repository"""
@property
def model(self):
"""model"""
return User
async def get_all(self):
"""get all"""
result = await db.session.scalars(select(self.model))
objs = [UserSchema.from_orm(i) for i in result.all()]
return objs
# the test case is as follows
@pytest.fixture()
def repo():
"""repo"""
return UserRepository()
@pytest.mark.asyncio
async def test_get_all(session, init_user, repo):
"""test get all"""
objs = await repo.get_all()
length = await session.scalar(select(func.count()).select_from(User))
assert len(objs) == length
Similar design
Based on
Develop
You may need to read the develop document to use SRC Layout in your IDE.
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
fastapi_sa-0.0.1.dev1.tar.gz
(5.9 kB
view details)
Built Distribution
File details
Details for the file fastapi_sa-0.0.1.dev1.tar.gz
.
File metadata
- Download URL: fastapi_sa-0.0.1.dev1.tar.gz
- Upload date:
- Size: 5.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.1 CPython/3.9.15
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 99922303f559e35a7f5ccc872efaa107a6d08652b5a1ea0d2cfd02365f8ccaa7 |
|
MD5 | a7ccdd44b8c358df100e9af981dd677d |
|
BLAKE2b-256 | cc9b006b5216ee26931309f75aca7897b060d053b468f609e1ae53d831a087f8 |
File details
Details for the file fastapi_sa-0.0.1.dev1-py3-none-any.whl
.
File metadata
- Download URL: fastapi_sa-0.0.1.dev1-py3-none-any.whl
- Upload date:
- Size: 5.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.1 CPython/3.9.15
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 5be1e5519779e31f2a7886fd87089bee6f03cc2583218a5f289a3fffe0594499 |
|
MD5 | 2e6321a52709663f68c88cc8d77cf196 |
|
BLAKE2b-256 | 703a44a6872d88ba5d66d8132aa2b490b7a5d1ee13cf390816b2f5f363ab6701 |