5.Flask-Migrate

5.Flask-Migrate

1.1. Project structure reconstruction

(1) config.py

DB_URI = "mysql+pymysql://root:123456@127.0.0.1:3306/flask_migrate?charset=utf8"

SQLALCHEMY_DATABASE_URI = DB_URI

(2) Create exts.py (to prevent circular references from reporting errors)

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

(3) Create models.py

from exts import db

class User(db.Model):
    __tablename__ ='user'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    username = db.Column(db.String(50),nullable=False)

(4) flask_migrate_demo.py

from flask import Flask
from exts import db
import config

app = Flask(__name__)
app.config.from_object(config)
db.init_app(db)

@app.route('/')
def hello_world():
    return'Hello World!'


if __name__ =='__main__':
    app.run()

 1.2. Use of flask-migrate

Flask-migrate is a package based on alembic and integrated into flask, and all migration operations are actually done by alembic. It can track changes in modules and map the changes to the database.

(1) Installation

pip install flask-migrate

 (2) manage.py

from flask_script import Manager
from flask_migrate_demo import app
from exts import db
import models #This must be imported
from flask_migrate import Migrate,MigrateCommand

manager = Manager(app)
Migrate(app,db)
manager.add_command("db",MigrateCommand) #Put all commands in db

if __name__ =='__main__':
    manager.run()

(3) Initialization

python manage.py db init

(4) Create a migration script

python manage.py db migrate -m'first commit'

(5) Generated to the database

python manage.py db upgrade

Directory Structure

Reference: https://cloud.tencent.com/developer/article/1172849 5. Flask-Migrate-Cloud + Community-Tencent Cloud