Alembic
1
Basic Alembic
Here is a step-by-step guide to using Alembic with SQLAlchemy for database migrations, using the same style of commands you mentioned:
1. Install Dependencies
First, install the required packages:
pip install sqlalchemy alembic2. Create a Simple Project Structure
Organize your project like this:
my_project/
├── app/
│ ├── __init__.py
│ ├── models.py
├── alembic/ # Alembic directory (auto-created)
├── alembic.ini
├── manage.py3. Initialize SQLAlchemy
app/__init__.py:
app/models.py:
4. Initialize Alembic
Run the following command to initialize Alembic:
This creates:
The
alembicdirectory (migration scripts live here).The
alembic.iniconfiguration file.
5. Configure Alembic
Open alembic.ini and set your database connection URL:
6. Set Up the Migration Environment
Modify the env.py file in the alembic directory to include your Base:
7. Run Commands
Use the manage.py script to run Alembic commands.
manage.py:
8. Generate and Apply Migrations
Run the following commands:
a. Autogenerate a Migration
b. Apply the Migration
c. Revert a Migration (Optional)
9. Verify Database Changes
Use a SQLite viewer or query the database to ensure the users table exists.
Notes:
Alembic automatically detects changes to the models when using
autogenerate=Trueinenv.py.You can manually edit migration files in the
alembic/versions/directory for complex schema updates.
This approach mirrors the workflow you described (db init, db migrate, db upgrade) using Alembic.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Last updated