Flask series tutorials (8) -- Flask-Migrate, flaskflask-migrate
Flask-Migrate
In the actual development environment, database changes often occur. Generally, we do not manually modify the database, but modify the database.ORM
The corresponding model, and then map the model to the database. At this time, it would be very useful to have a tool dedicated to this kind of thing.flask-migrate
This is what we do.flask-migrate
Is based onAlembic
And integratedFlask
And all the Migration Operations areAlembic
By doing so, he can track model changes and map changes to the database.
UseFlask-Migrate
To install the SDK, run the following command:
pip install flask-migrate
To makeFlask-Migrate
Ability to manageapp
To useMigrate(app,db)
To bindapp
And database. Assume that the followingapp
File:
From flask import Flaskfrom flask_sqlalchemy import SQLAlchemyfrom constants import DB_URIfrom flask_migrate import Migrateapp = Flask (_ name _) app. config ['sqlalchemy _ DATABASE_URI '] = DB_URIapp.config ['sqlalchemy _ TRACK_MODIFICATIONS'] = Truedb = SQLALCHEMY (app) # bind the app and database migrate = Migrate (app, db) class User (db. model): id = db. column (db. integer, primary_key = True) username = db. column (db. string (20) ad Dresses = db. relationship ('address', backref = 'user') class Address (db. model): id = db. column (db. integer, primary_key = True) email_address = db. column (db. string (50) user_id = db. column (db. integer, db. foreignKey ('user. id ') db. create_all () @ app. route ('/') def hello_world (): return 'Hello World! 'If _ name _ = '_ main _': app. run ()
Then, you can mapORM
. To operate the currentflask app
First, you needapp
Import to environment variables:
# windows$env:FLASK_APP='your_app.py'#linux/unixexport FLASK_APP='your_app.py'
Set the currentapp
After being imported to environment variables, You need to initialize a migration Folder:
flask db init
Then add the current model to the migration file:
flask db migrate
Finally, map the database operations in the migration file to the database:
flask db upgrade
The above is done by loading the currentapp
Environment variables. There is also a way to directly passflask-script
. Now refactor the previous project and set it to the following directory structure:
! [Flaskmigrate project directory structure] (/assets/migrate. png)
The functions of each file are described as follows:
Constants. py file:Constant file used to store database configurations.
# constants.pyHOSTNAME = '127.0.0.1'PORT = '3306'DATABASE = 'xt_flask_migrate'USERNAME = 'root'PASSWORD = 'root'DB_URI = 'mysql+mysqldb://{}:{}@{}:{}/{}'.format(USERNAME,PASSWORD,HOSTNAME,PORT,DATABASE)
Ext. py file:Setdb
Put variables in a separate file, instead of in the masterapp
File. The purpose isdb
When referenced by multiple model filesfrom your_app import db
Howeveryour_app.py
Classes defined in the model file will also be introduced, which leads to circular references. Therefore, the best way is to place it in an independent file that does not depend on other modules.
# ext.pyfrom flask_sqlalchemy import SQLAlchemydb = SQLAlchemy()
Models. py file:Model files are used to store all models. Note thatflask-script
You do not need to usedb.create_all()
To create a database.
# models.pyfrom ext import dbclass User(db.Model): id = db.Column(db.Integer,primary_key=True) username = db.Column(db.String(50)) addresses = db.relationship('Address',backref='user') def __init__(self,username): self.username = usernameclass Address(db.Model): id = db.Column(db.Integer,primary_key=True) email_address = db.Column(db.String(50)) user_id = db.Column(db.Integer,db.ForeignKey('user.id')) def __init__(self,email_address): self.email_address = email_address
Manage. py file:This file is used to store commands for ing databases,MigrateCommand
Yesflask-migrate
An integrated command, so to add it to the script command, you must usemanager.add_command('db',MigrateCommand)
To run laterpython manage.py db xxx
Is to executeMigrateCommand
.
# manage.pyfrom flask_migrate import Migrate,MigrateCommandfrom ext import dbfrom flask_script import Managerfrom flask import Flaskfrom constants import DB_URIimport modelsapp = Flask(__name__)app.config['SQLALCHEMY_DATABASE_URI'] = DB_URIapp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = Truedb.init_app(app)migrate = Migrate(app,db)manager = Manager(app)manager.add_command('db',MigrateCommand)if __name__ == '__main__': manager.run()
Flaskmigrate. py file:This is the masterapp
File. And becausedb
Put in another file, so usedb.init_app(app)
To bind the database.
# flaskmigrate.pyfrom flask import Flaskfrom ext import dbapp = Flask(__name__)db.init_app(app)@app.route('/')def hello_world(): return 'Hello World!'if __name__ == '__main__': app.run()
Run the following command to initialize the migration file:
python manage.py db init
Run the following command to add the model ing to the file:
python manage.py db migrate
Finally, add the ing file to the database:
python manage.py db upgrade
### If you want to learn more about Flask, watch our free Flask tutorial video: getting started with the project