Tutorial on using Flask-migrate to extend the migration database in the Python flask framework

Source: Internet
Author: User
When we upgrade the system, we often encounter the need to update the server-side data structure, and so on, the way is by hand-written alter SQL script processing, often found missing, resulting in the program published to the server will not work properly.

Now we can use the Flask-migrate plugin to solve it, flask-migrate plug-in is based on alembic,alembic is a data migration tool developed by the famous SQLAlchemy author.

Here's how:

1. Installing the Flask-migrate Plugin

$ pip Install Flask-migrate

2. Modify the code in the Flask app section to add migrate-related command

db = SQLAlchemy (APP) migrate = Migrate (app, db) Manager = Manager (APP) Manager.add_command (' db ', Migratecommand)

3. Initialization

$ Python app.py db init

Migrating a database using Flask-migrate
As the development progresses, you will find that your database model needs to be changed, and the database needs to be updated when this happens.

Flask-sqlalchemy the only way to update a table is to destroy the old table if the database tables do not exist, which will cause the loss of data in all databases.

A better solution would be to use a database migration framework. The database Migration Framework tracks changes to the database model and then applies incremental changes to the database, just as the source version control tool tracks changes to the source files.

SQLAlchemy's main developer wrote a Alembic migration framework, but we don't use the Alembic,flask app directly to use flask-migrate extensions, A lightweight Alembic package that integrates flask-script to provide all operational commands.

4. Create a migration warehouse

First, the flask-migrate must already be installed in the virtual environment:

(venv) $ pip Install Flask-migrate

The following shows how the extension is initialized:

From flask.ext.migrate import migrate, Migratecommand # ... migrate = migrate (app, db) Manager.add_command (' db ', Migratecommand)

In order to use the Database Migration command, Flask-migrate provides the Migratecommand class to connect Flask-script Manager objects. In this example, DB is used to connect to the command.

Before the database migration can be maintained, a migration library must be created through the INIT subcommand:

(venv) $ Python hello.py db init

Creating Directory/home/flask/flasky/migrations...done Creating directory/home/flask/flasky/migrations/versions ... done Generating/home/flask/flasky/migrations/alembic.ini...done generating/home/flask/flasky/migrations/ Env.py...done Generating/home/flask/flasky/migrations/env.pyc...done generating/home/flask/flasky/migrations/ Readme...done Generating/home/flask/flasky/migrations/script.py.mako...done Please edit configuration/connection/ Logging settings in '/home/flask/flasky/migrations/alembic.ini ' before proceeding.

This command creates a migrations folder that contains all the migration scripts.

Recommendation: If you have cloned apps on GitHub, you can now run git checkout 5c to switch to this version of the app.

5. Create a migration script

In Alembic, the database migration work is done by the migration script. This script has two functions, called upgrade () and downgrade () respectively. The upgrade () function enforces database changes, is part of the migration, and the downgrade () function deletes them. By adding and removing the ability to change the database, Alembic can reconfigure the database from any point in time in the history.

Alembic migrations can be created manually or automatically using the revision and migrate commands, respectively. Manual migration creates a migration framework script through the empty upgrade () and downgrade () functions implemented by the developer using Alembic's operations object directives. On the other hand, automatic migration generates code for upgrade () and downgrade () by looking for differences between the model definition and the current state of the database.

Warning: Automatic migrations are not always accurate, and some details can be ignored. Therefore, you should always review the automatically generated migration scripts.
The MIGRATE subcommand creates an automatic migration script:

(venv) $ python hello.py db migrate-m "initial migration"

INFO [alembic.migration] Context impl sqliteimpl.info [alembic.migration] would assume non-transactional Ddl.info [ Alembic.autogenerate] detected added table ' roles ' info [alembic.autogenerate] detected added table ' users ' info [ Alembic.autogenerate.compare] Detected added index ' ix_users_username ' on ' [' username '] ' Generating/home/flask/flasky /MIGRATIONS/VERSIONS/1BC 594146bb5_initial_migration.py...done

Recommendation: If you have cloned apps on GitHub, you can now run git checkout 5c to switch to this version of the app. Note that you do not need to generate migrations for this app, and all migration scripts are included in the repository.
6. Updating the database

Once the migration script is reviewed and accepted, it can be updated to the database using the DB Upgrade command:

(venv) $ python hello.py db upgrade

INFO [alembic.migration] Context impl sqliteimpl.info [alembic.migration] would assume non-transactional Ddl.info [ Alembic.migration] Running Upgrade None-1BC594146BB5, initial migration

The first migration is actually the equivalent of calling Db.create_all (), but in subsequent migrations, the upgrade command implements the update operation on the table without affecting the contents of the table.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.