Chapter 11. Getting Started with Alembic
Alembic provides a way for us to programmically create and perform migrations to handle changes to the database that we’ll need to make as our application evolves. For example, we might add columns to our tables or remove attributes from our models. We might also add entirely new models, or split an existing model into multiple models. Alembic provides a way for us to preform these types of changes by leveraging the power of SQLAlchemy.
To get started, we need to install Alembic, which we can do with the following:
pip install alembic
Once we have Alembic installed, we need to create the migration environment.
Creating the Migration Environment
To create the migration environment, we are going to create a folder labeled CH12, and change into that directory. Next, run the alembic init alembic
command to create our migration environment in the alembic/ directory. People commonly create the migration environment in a migrations/ directory, which you can do with alembic init migrations
. You can choose whatever directory name you like, but I encourage you to name it something distinctive that won’t be used as a module name in your code anywhere. This initialization process creates the migration environment and also creates an alembic.ini file with the configuration options. If we look at our directory now, we’ll see the following structure:
. ├── alembic │ ├── README │ ├── env.py │ ├── script.py.mako │ └── versions └── alembic.ini
Get Essential SQLAlchemy, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.