GithubHelp home page GithubHelp logo

riley-ashton / fastapi-sqlmodel Goto Github PK

View Code? Open in Web Editor NEW
0.0 1.0 0.0 75 KB

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

License: MIT License

Dockerfile 2.71% Python 94.50% Mako 2.79%
alembic docker fastapi poetry postgresql sqlite sqlmodel

fastapi-sqlmodel's Introduction

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: [email protected] 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:

fastapi-sqlmodel's People

Contributors

riley-ashton avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.