SQLModel
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.
Add it to the non_ver_reqs.txt
file:
And freeze the requirements:
SQLite
Add the path to the SQLite database file in the projects core settings:
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:
As 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:
Use 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.py
Now create a project level directory for database Python code:
Add the following file and code to handle creating the database and session: