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 poetry
curl -sSL https://install.python-poetry.org | python3 -
# create SECRET for jwt
cd backend
openssl rand -hex 32 > SECRET_KEY
# install packages
poetry installNo docker, no postgres. Just sqlite. Starts on port 8000.
cd backend
poetry shell
LOCAL_DEV=1 uvicorn app.main:app --reloadDB Browser for Sqlite is a tool similar to PGAdmin, but for sqlite databases.
Runs the fastapi server on port 8004.
$ docker-compose up -d --build
$ docker-compose exec web alembic upgrade headdocker-compose exec web alembic revision --autogenerate
docker-compose exec web alembic upgrade headusername: postgres@test.com password: postgres
Open the backend/ folder in your IDE
and point the python interpreter to poetry
Shows dependency graph of the backend
poetry shell
# cluster external dependencies (simplifies)
pydeps app --clusterdb.pycontains functions to start the db and get an async session.models.pycontains 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. Limitingmodels.pyto pydantic models and creatingschema.pyor similar for SqlAlchemy divides concerns, but is more complicated.auth.pyfunctions dedicated to authorization and authentication. Handles persistence too (potentially too broad in scope).crud.pygeneric 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.pybrings fastapi in to route everything. Only file to depend on fastapi. Bigger projects may break this up into multiple routers.test_wrapper.pyprovides an async client wrapper for running tests. Async client is user aware, and handles header tokens - just specify the user.test.pythe actual test cases. Useswrapperfromtest_wrapper.py
- add models (copy form of
SongandSongBase) tomodels.py.SongBaseinherits fromSQLModeland 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.Songinherits fromOwnedandSongBase, as well as specifyingtable=Trueto create a table in the database. InheritingOwnedmeans it is aware of uuids and user ids. - add business logic either directly to
main.pyroutes (simple cases) or create a new file to hold complex logic. Consider naming it after the model. Either way, use the functions incrud.pyfor persistence. Ifcrud.pyis used, the models passed do not need to haveuser_idset, it will set itself from the user id of thetoken. - add model to
target_metdatainbackend/migrations/env.py - add test fixtures to
test_wrapper.py - 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())FastApi + SqlModel + Alembic - also - Article
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 updateNote: poetry does not work in a folder with __init__.py
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
- use files for secrets instead of environment variables
- environment variables are more prone to leaking
- files can be protected by OS permissions
- blog post
Helpful random bits of info: