Skip to content

An example python web stack repo using fastapi, sqlmodel and alembic

License

Notifications You must be signed in to change notification settings

riley-ashton/fastapi-sqlmodel

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Multi-Tenant FastAPI + SQLModel

Sample FastAPI project that uses async SQLAlchemy, SQLModel, Postgres, Alembic, and Docker.

There is two development modes: full-fledged docker (postgres) or simple (with sqlite and no docker).

Install

# install poetry
curl -sSL https://install.python-poetry.org | python3 -

# create SECRET for jwt
cd backend
openssl rand -hex 32 > SECRET_KEY

# install packages
poetry install

Simple Local Development

No docker, no postgres. Just sqlite. Starts on port 8000.

cd backend
poetry shell
LOCAL_DEV=1 uvicorn app.main:app --reload

DB Browser for Sqlite is a tool similar to PGAdmin, but for sqlite databases.

Docker (w/Postgres) Development

Runs the fastapi server on port 8004.

$ docker-compose up -d --build
$ docker-compose exec web alembic upgrade head

Migration

docker-compose exec web alembic revision --autogenerate
docker-compose exec web alembic upgrade head

PGAdmin

localhost:8005

username: postgres@test.com password: postgres

Use in IDEs

Open the backend/ folder in your IDE
and point the python interpreter to poetry

Pydeps

Shows dependency graph of the backend

install graphviz

poetry shell

# cluster external dependencies (simplifies)
pydeps app --cluster

Architecture

  • db.py contains functions to start the db and get an async session.
  • models.py contains the models as SqlModel objects. Ideally this would be domain entities, without concerns like persistence. It is far simpler to define these in one file, at the sacrifice of binding the models to the SQLModel ORM. Limiting models.py to pydantic models and creating schema.py or similar for SqlAlchemy divides concerns, but is more complicated.
  • auth.py functions dedicated to authorization and authentication. Handles persistence too (potentially too broad in scope).
  • crud.py generic CRUD functions that are user aware and scope db calls to a user. User code does not need to know about handling tokens, users, etc.
  • main.py brings fastapi in to route everything. Only file to depend on fastapi. Bigger projects may break this up into multiple routers.
  • test_wrapper.py provides an async client wrapper for running tests. Async client is user aware, and handles header tokens - just specify the user.
  • test.py the actual test cases. Uses wrapper from test_wrapper.py

Adding Routes / Models

  1. add models (copy form of Song and SongBase) to models.py. SongBase inherits from SQLModel and has no table in the database; it is unaware of uuids or user ids. Often used for client facing when creating, or returning simplified models. Song inherits from Owned and SongBase, as well as specifying table=True to create a table in the database. Inheriting Owned means it is aware of uuids and user ids.
  2. add business logic either directly to main.py routes (simple cases) or create a new file to hold complex logic. Consider naming it after the model. Either way, use the functions in crud.py for persistence. If crud.py is used, the models passed do not need to have user_id set, it will set itself from the user id of the token.
  3. add model to target_metdata in backend/migrations/env.py
  4. add test fixtures to test_wrapper.py
  5. add test to test.py

Trick:

song_base: SongBase = SongBase(...)
song: Song = Song(**song_base.dict())

song2: Song = Song(...)
song_base2: SongBase = SongBase(**song2.dict())

Future Stuff

References

FastApi + SqlModel + Alembic - also - Article

fastapi-react

Full stack fastapi (outdated)

python code quality

python testing

Authentication

similar

Alembic migrations

Poetry

Poetry is used for dependency management. Full docs here, but below is the basics:

# using environment
poetry shell

# installing
poetry add package-name
poetry add "package-name[extras]"

# installing (dev)
poetry add -G dev package-name

# updating packages
poetry update

Note: poetry does not work in a folder with __init__.py

Task Queue

FastApi's background tasks are used for backgrounds tasks.

Future options are

  • ray serve (for CPU/GPU bound tasks; good for ML applications)
  • celery + flower
  • arq
from fastapi.concurrency import run_in_threadpool
res = await run_in_threadpool(cpu_bound_task, contents)

https://stackoverflow.com/questions/71516140/

https://www.anyscale.com/blog/serving-pytorch-models-with-fastapi-and-ray-serve

Secrets in files, not environment variables

  • use files for secrets instead of environment variables
  • environment variables are more prone to leaking
  • files can be protected by OS permissions
  • blog post

CI Stuff

Usage Info

Helpful random bits of info:

About

An example python web stack repo using fastapi, sqlmodel and alembic

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages