Use Flask to write a light blog (8)-(M) Vc_alembic manage the upgrade and demotion of the database structure

Source: Internet
Author: User

Directory

    • Directory
    • List of previous texts
    • Extended Reading
    • Alembic
    • View available options for Command Manager DB
    • Initialize DB Migrate
    • Start tracking for the first time
    • To apply a record file to a database to upgrade the database structure in real time
    • Roll back to a record environment

List of previous texts

Use Flask to write a light blog (1)-Create a project
Use Flask to write a light blog (2)-hello world!
Use Flask to write a light blog (3)-(M) vc_ connect MySQL and SQLAlchemy
Use Flask to write a light blog (4)-(M) vc_ creating data models and tables
Use Flask to write a light blog (5)-(M) Vc_sqlalchemy's CRUD explanation
Use Flask to write a light blog (6)-(M) vc_models relationship (one to many)
Use Flask to write a light blog (7)-(M) vc_models relationship (many to many)

Extended Reading

Openstack_sqlalchemy Modifying the table structure of a database
Openstack_sqlalchemy_ Multi-table insert implementation for a one-to-many relationship table

Alembic

In most cases, the design of the database is completed before you begin implementing the code for a new project. However, as the new functionality of the project increases or needs change, the inevitable modification of the data model will be consistent throughout the development of the project . There is a problem here: How to migrate the data model updates from the development environment to the production environment in order to update the database structure or roll back the database to a previous point in order to replicate the environment, while maintaining the integrity of the existing data.

Alembic (Database migration data Migration tracking record) provides the ability to upgrade and downgrade the databases, which can help us to solve the above problems. It can achieve the same effect as Git manages project code.

    • Here we use the Flask extension flask-migrate
      Note: To install in a virtualenv environment
pip install Flask-Migratepip freeze > requirements.txt
    • Generate Manager DB Directives
      Create a new commands in the manage.py file:manager.add_command("db", MigrateCommand)
 fromFlask.ext.scriptImportManager, Server fromFlask.ext.migrateImportMigrate, MigratecommandImportMainImportModels# Init Manager Object via App objectManager = Manager (Main.app)# Init Migrate object via app and DB objectMigrate = Migrate (Main.app, models.db)# Create Some new commandsManager.add_command ("Server", Server ()) Manager.add_command ("DB", Migratecommand)@manager. Shell def make_shell_context():    "" " Create a python CLI. Return:default Import Object type: ' Dict ' "" "    returnDict (App=main.app, Db=models.db, User=models. User, Post=models. Post, Comment=models.comment, Tag=models. TAG)if__name__ = =' __main__ ': Manager.run ()
View available options for Command Manager DB
(ENV) [email protected] jmilkfan-s-blog]# python manage.py dbperform database migrationspositional arguments: {upgrade,heads , Merge, Migrate,stamp,show,Current, edit,init,downgrade,branches,history,revision} Upgrade upgrade  to a later version heads Show  Current Available He Ads  in the script directory mergemerge revisions together.               Creates a new migration file migrate Alias  for ' revision--autogenerate ' stamp ' stamp ' the revision table  with the given revision;               Don ' t run any migrationsShow                ShowThe revision denoted byThe given symbol. CurrentDisplay the CurrentRevision for  each Database. Edit edit CurrentRevision. Init creates a new migration repository downgrade Revert toA previous version branchesShow  CurrentBranch points history List changeset scriptsinchChronologicalOrder. RevisionCreateA new revision file.
Initialize DB Migrate
(ENV) [[email protected] jmilkfan-s-blog]# python manage.py db initCreating directory/opt/jmilkfan-s-blog/migrations...Done Creating Directory/opt/jmilkfan-s-blog/migrations/versions...Done Generating/opt/jmilkfan-s-blog/migrations/readme...Done Generating/opt/jmilkfan-s-blog/migrations/alembic.ini...Done generating/opt/jmilkfan-s-blog/migrations/env.py...Done Generating/opt/jmilkfan-s-blog/migrations/script.py.mako...Done GENERATING/OPT/JMILKFAN-S-BLOG/MIGRATIONS/ENV.PYC...Done please edit configuration/connection/logging settingsinch '/opt/jmilkfan-s-blog/migrations/alembic.ini 'Before proceeding.

After initializing the database update task, a migrations directory is created, and all the change log files (which are originally Python files) will be saved in the directory.

Start tracking for the first time
(env) [[email protected] JmilkFan-s-Blog]# python manage.py db migrate -m "Initial migration"INFO  [alembic.runtime.migration] Context impl MySQLImpl.INFO  [alembic.runtime.migration] Will assume non-transactional DDL.INFO  [alembic.envin schema detected.

This instructs Alembic to scan all SQLAlchemy objects and record rows and columns that are not recorded as a Python file and save it to the migrations/versions path.

Applying a record file to a database (real-time database structure upgrade)

Note 1: The command is executed only if the record file must exist under the Migrations/versions directory.
Note 2: And these record files can be manually modified and created, which is also a way to update the database structure in real time. Update the database structure that needs to be modified, manually write to the record file, then execute the upgrade instruction to implement the database update, and these updates can be in bulk in the database, do not need to use a single SQL statement to modify.

(env) [[email protected] JmilkFan-s-Blog]# python manage.py db upgradeINFO  [alembic.runtime.migration] Context impl MySQLImpl.INFO  [alembic.runtime.migration] Will assume non-transactional DDL
Roll back to a record environment

The usage is very similar to Git:

# 获取 History ID(env) [[email protected] JmilkFan-s-Blog]# python manage.py db history# 回滚到某个 history(env) [[email protected] JmilkFan-s-Blog]# python manage.py db downgrade 

Use Flask to write a light blog (8)-(M) Vc_alembic manage the upgrade and demotion of the database structure

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.