Skip to main content

fastapi-sa provides a simple integration between FastAPI and SQLAlchemy in your application

Project description

fastapi-sa

GitHub Workflow Status (branch) GitHub Python PyPI Codacy Badge codecov

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


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.2.0.tar.gz (5.1 kB view details)

Uploaded Source

Built Distribution

fastapi_sa-0.2.0-py3-none-any.whl (5.9 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_sa-0.2.0.tar.gz.

File metadata

  • Download URL: fastapi_sa-0.2.0.tar.gz
  • Upload date:
  • Size: 5.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.6

File hashes

Hashes for fastapi_sa-0.2.0.tar.gz
Algorithm Hash digest
SHA256 aae0e21022ac5089b58faf66ae88a9dd17037624c9b4da9b9ea4637458420de3
MD5 da7d660b22b0f6dbac8cf93e73e43486
BLAKE2b-256 6a60fdce1d71b55228936cc06f8374bd02bffeefad212a978c9d50b76dcaf038

See more details on using hashes here.

File details

Details for the file fastapi_sa-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: fastapi_sa-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 5.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.6

File hashes

Hashes for fastapi_sa-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 dbd6ea9fbf8d6ef3b1d701cfb6d747f95423400d1ed3ecb40466aa3272a94191
MD5 d8a717c8b21b39ffddc122b7f0678380
BLAKE2b-256 6ef215a3087a5c5a599243c73c86372452e4e644d6d2ab75c6e5313bba7067a4

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page