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.
Metadata
Release files for fastapi-sa 0.2.0
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 | Actions |
|---|---|---|---|---|
| fastapi_sa-0.2.0.tar.gz | 5.1 kB | Without provenance | Details for fastapi_sa-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fastapi_sa-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for fastapi_sa-0.2.0-py3-none-any.whl |
Total release size: 11.0 kB
Release files / fastapi_sa-0.2.0.tar.gz
| Download URL | fastapi_sa-0.2.0.tar.gz |
|---|---|
| Size | 5.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
aae0e21022ac5089b58faf66ae88a9dd17037624c9b4da9b9ea4637458420de3
|
|
BLAKE2b-256 checksum How to use checksums |
6a60fdce1d71b55228936cc06f8374bd02bffeefad212a978c9d50b76dcaf038
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/4.0.2 CPython/3.11.6
|
Release files / fastapi_sa-0.2.0-py3-none-any.whl
| Download URL | fastapi_sa-0.2.0-py3-none-any.whl |
|---|---|
| Size | 5.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
dbd6ea9fbf8d6ef3b1d701cfb6d747f95423400d1ed3ecb40466aa3272a94191
|
|
BLAKE2b-256 checksum How to use checksums |
6ef215a3087a5c5a599243c73c86372452e4e644d6d2ab75c6e5313bba7067a4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/4.0.2 CPython/3.11.6
|
Security for fastapi-sa 0.2.0
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.
To learn more about protecting yourself from malicious actors, visit our package security documentation.