Flask series tutorials (8) -- Flask-Migrate, flaskflask-migrate

Source: Internet
Author: User

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.ORMThe 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-migrateThis is what we do.flask-migrateIs based onAlembicAnd integratedFlaskAnd all the Migration Operations areAlembicBy doing so, he can track model changes and map changes to the database.

UseFlask-MigrateTo install the SDK, run the following command:

pip install flask-migrate

To makeFlask-MigrateAbility to manageappTo useMigrate(app,db)To bindappAnd database. Assume that the followingappFile:

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 appFirst, you needappImport to environment variables:

# windows$env:FLASK_APP='your_app.py'#linux/unixexport FLASK_APP='your_app.py'

Set the currentappAfter 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 currentappEnvironment 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:SetdbPut variables in a separate file, instead of in the masterappFile. The purpose isdbWhen referenced by multiple model filesfrom your_app import dbHoweveryour_app.pyClasses 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-scriptYou 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,MigrateCommandYesflask-migrateAn integrated command, so to add it to the script command, you must usemanager.add_command('db',MigrateCommand)To run laterpython manage.py db xxxIs 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 masterappFile. And becausedbPut 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

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.