A simple app that I am using to become more familiar with FastAPI and more particularly, SQLModel.
(This code was essentially built from the documentation available for SQLModel here)
- Clone this repository and navigate into it.
git clone git@github.com:joemudryk/learning-sqlmodel.git
cd learning-sqlmodel- Then run with either docker or a python virtual environment
To run the app using just docker, you can call the script
# docker will need to be installed
./scripts/run_with_docker.sh# python3.9 is recommended
python -m venv venv
source venv/bin/activate
pip install -r requirements
python main.pyAfter running the app, then navigate to http://0.0.0.0:8080 to interact with the API.
An example of using alembic to update the database keeping up to date with the models
Example of updating a SQLModel
classHeroBase(SQLModel):
name: strsecret_name: strage: Optional[int] =Nonepower: Optional[str] =None# NewclassHero(HeroBase, table=True):
id: Optional[int] =Field(default=None, primary_key=True)Note: Be sure that the new class variable is either Optional or has a default value. This is so alembic can back populate entries in the database if needed.
Also make sure the models you are using are imported in migrations/env.py
python -m alembic revision --autogenerate -m "Add power to Hero model"Or use the autogenerate_migration.sh script in the scripts directory, saves a bit of typing.
python-malembicupgradeheadAnd Bob's your Aunty. A fairly simplistic way of using SQLModel with alembic :)