Using databases


Making data persistent is an essential part of a development skillset. We will be using SQL-based databases and SQLAlchemy as a Python SQL Toolkit and Object Relational Mapperopen in new window.

An Object Relational Mapper, or ORM, has tools to convert ("map") between objects in code and database tables ("relations"). With an ORM, you normally create a class that represents a table in a SQL database, each attribute of the class represents a column, with a name and a type.

For example a class Pet could represent a SQL table pets. And each instance object of that class represents a row in the database. An object orion_cat (an instance of Pet) could have an attribute orion_cat.type, for the column type. And the value of that attribute could be, e.g. "cat". These ORMs also have tools to make the connections or relations between tables or entities.

SQLAlchemy can be used with multiple SQL dialects and databases, listed hereopen in new window. However, for this course we will be using SQLiteopen in new window, an open-source, almost zero-configuration, library-contained, database engine. This means that you do not need to install any database engine to run on your machine, including the library in your application code is enough. The entire database will then be contained in a single .db-file. SQLite is often used in simple applications, embedded devices, mobile phones, televisions, ...

Sqlite vs Sql

Most of the code in this section is actually SQLAlchemy code, mixed in with a couple of parts of FastAPI. Due to that it is more lengthy than the usual FastAPI way of working and requires multiple .py-files. Following along in the next chapters:

Last update: 11/15/2022, 7:11:41 PM