SQLAlchemy
Introduction
These docs written for sqlalchemy == 2.0
- 🏠 SQLAlchemy Home
- 📖 SQLAlchemy Docs Index
- 📄 SQLAlchemy ORM Quick Start
- Learn the new 2.0 syntax with a guided tutorial/quickstart.
- 📄 SQLAlchemy Unified Tutorial
- The 2.0 release of SQLAlchemy introduced a new ORM syntax. It is different enough from versions prior to 2.0 that a tutorial demonstrating the "old" and "new" ways of doing things was needed.
- The newer 2.0 syntax is simpler and more Pythonic, and feels more flexible (subjective opinions).
- 📄 SQLAlchemy ORM Quick Start
Sample Code
Check the pages in this section for sample code & explanations for using SQLAlchemy in your app.
Note
Check my red-utils package's .ext.sqlalchemy_utils module for an example database module. You can essentially copy/paste the code into a directory in your project like src/app/database/.
Full sample: From initializing DBSettings to adding an entity
When setting SQLAlchemy up in a new project, you must lay some groundwork first. You need to create a Base class that your models will inherit from, and you need to configure an engine & session pool. Repository classes are optional, but highly recommended to control reading from/writing to the database.
The guide below assumes you have created a directory in your project called db/ to store all the SQLAlchemy code.
Setup SQLAlchemy configuration
Todo
- Section for loading from
dynaconf - Section for loading from env with
os.getenv() - Creating a
DBSettingsclass
Create engine & session pool
Todo
- Creating an engine
- Creating a session pool
Create your SQLAlchemy and repository Base classes
In your db/ directory, create a file called base.py. This file is where you will configure your SQLAlchemy Base class, as well as any other base classes for the app like BaseRepository:
When creating new database model classes, you will inherit from this Base class. For example, to create a User model in a file called models.py:
Similarly, the BaseRepository class can be inherited from when creating a UserRepository class to handle CRUD operations on the User model:
Committing a User to the database
Todo
- Example converting a dict to a
Userclass - Example of creating a
session_pool - Example of using a repository to commit a
Userto the database