Flask-migrate is an extension tool for handling SQLAlchemy database migrations. Manage database changes with migrate when model changes occur.
Migrate has 3 main actions, INIT, migrate and upgrade.
Take the following application as an example:
1 fromFlaskImportFlask2 fromFlask_sqlalchemyImportSQLAlchemy3 fromFlask_migrateImportMigrate4 5App = Flask (__name__)6app.config['Sqlalchemy_database_uri'] ="sqlite:///app.db"7 8db =SQLAlchemy (APP)9Migrate =Migrate (app, DB)Ten One #Model A classUser (db. Model): -ID = db. Column (db. Integer, primary_key=True) -Name = db. Column (db. String (128))
1. Initialization
Flask DB Init
This command generates a Migrations folder in the current directory. This folder also needs to be added to version control along with other source files.
2. Generate the initial migration
Flask DB Migrate
This command generates a version folder under Migrations, which contains the corresponding versions of the database Operations py script.
Since migrate does not necessarily find all of your changes to the model, the generated py script needs to be review and edit if necessary.
For example, the table name table, the column name change, or the naming of constraints are not found. For more details of the restrictions see this: Alembic autogenerate documentation
3. Database Upgrade
Flask DB Upgrade
A final step. This command is equivalent to executing the corresponding PY version under the version folder and making a change operation to the database.
Since then, the model has changed, as long as the repeated migrate and upgrade operation can be.
To view the Help documentation:
Flask DB--help
Using Flask-script's command call, refer to the official documentation yourself: flask-migrate documentation
[Python] Flask-migrate Simple Introduction