SQLModel
Notes// archive From the original Code Walker docs. Kept for reference, so some versions and commands may be out of date.
As already touched on, SQLModel is a library for interacting with SQL databases from Python code with Python objects. SQLModel is intuitive, easy to use, highly compatible, and robust. From my adventures, this library seems the most logical approach for working with databases in FastAPI.
See https://sqlmodel.tiangolo.com/
Install#
Install sqlmodel using pip and remember to freeze this to the requirements files.
pip install sqlmodelAdd it to the non_ver_reqs.txt file:
fastapi
uvicorn[standard]
pydantic-settings
sqlmodelAnd freeze the requirements:
pip freeze > requirements.txtVersion of SQLModel at time of writing sqlmodel==0.0.22
SQLite#
Add the path to the SQLite database file in the projects core settings:
CONFIG_MAIN_APP_SQLITE: str = "sqlite:///mnt/db/exampleforyou.sqlite3"When working with SQLite, you work with a single local file. This SQLite file will live in a volume mount location. Create a new directory external to your project directory to store the database, for example:
mkdir -p ~/volumes/dbAs already demonstrated when adding certificates, moving forward with this project, any external volume that needs to be mounted will be done under a project directory called mnt. If not already done, create this directory in the root of you project:
mkdir mntWhen working locally, create a soft link:
ln -s ~/volumes/db mnt/dbUse tree -I venv to list the structure of your project via the command line.
The project tree should look something like this:
.
├── api
│ └─ health_api.py
├── main.py
├── mnt
│ └── db -> /home/USERNAME/volumes/certs
│ └── certs -> /home/USERNAME/volumes/db
├── non_ver_reqs.txt
├── requirements.txt
└── settings
└── config.pyNow create a project level directory for database Python code:
mkdir dbAdd the following file and code to handle creating the database and session:
from sqlmodel import create_engine, Session
from config.settings import settings
engine = create_engine(
settings.CONFIG_MAIN_APP_SQLITE,
connect_args={"check_same_thread": False},
echo=True
)
def get_session_db():
with Session(engine) as session:
yield session