miguelgrinberg Flask-Migrate: SQLAlchemy database migrations for Flask applications using Alembic

The head alias always points to the most recent migration, which in our case is the first and only one currently in the repository. To understand the problem you have to think about how Alembic (the migration flask developer engine used by Flask-Migrate) generates database migrations. The contents of a migration are obtained by running a comparison between the current model definitions and the current schema of your database.

Notice, that in addition to revision ID, alembic also keeps track of down_revision ID. This way alembic is able to upgrade and downgrade database migrations in the correct order. The trick to generate this initial migration for a project that uses an up to date database is to temporarily switch to an empty database, just for the flask db migrate command. In my projects I use a DATABASE_URL environment variable to configure the location of the database.

Creating seed data in a flask-migrate or alembic migration

The User class created above will represent users stored in the database. The class inherits from db.Model, a base class for all models from Flask-SQLAlchemy. These are the columns that will be created in the corresponding database table.

flask migration

This command effectively restores the tables that were downgraded above. Since database migrations do not preserve the data stored in the database, downgrading and then upgrading has the effect of quickly emptying all the tables. The first command tells Flask-Migrate to apply the database migrations in reverse order. When the downgrade command is not given a target, it downgrades one revision. The base target causes all migrations to be downgraded, until the database is left at its initial state, with no tables. The migration script needs to be reviewed and edited, as Alembic is not always able to detect every change you make to your models.

Database Relationships

Calling the all() method of the results object converts the results to a plain list. Are you wondering how do all these database operations know what database to use? The application context that was pushed above allows Flask-SQLAlchemy to access the Flask application instance app without having to receive it as an argument. The extension looks in the app.config dictionary for the SQLALCHEMY_DATABASE_URI entry, which contains the database URL. I have made you suffer through a long process to define the database, but I haven’t shown you how everything works yet.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *