Flask-Migrate
一、安装 Flask-Script 和 Flask-Migrate
新建一个FLask 项目
目录如下:
下面是主要py文件的内容
__init__.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from flask_sqlalchemy import SQLAlchemy 2 from flask import Flask 3 from My_app.views.user import user 4 from My_app.views.uerlist import userlist 5 6 db = SQLAlchemy() 7 8 9 def create_app(): 10 app = Flask(__name__) 11 app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:@127.0.0.1:3306/bms?charset=utf8' 12 13 # SQLALCHEMY_POOL_SIZE 配置 SQLAlchemy 的连接池大小 14 app.config["SQLALCHEMY_POOL_SIZE"] = 5 15 16 # SQLALCHEMY_POOL_TIMEOUT 配置 SQLAlchemy 的连接超时时间 17 app.config["SQLALCHEMY_POOL_TIMEOUT"] = 15 18 app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False 19 20 db.init_app(app) 21 app.register_blueprint(user) 22 app.register_blueprint(userlist) 23 24 return app
models.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from My_app import db 2 3 4 class User(db.Model): 5 __tablename__ = "user" 6 __table_args__ = {"useexisting": True} 7 8 id = db.Column(db.Integer, primary_key=True) 9 name = db.Column(db.String(32)) 10 11 12 if __name__ == '__main__': 13 from My_app import create_app 14 my_app = create_app() 15 16 db.drop_all(app=my_app) 17 db.create_all(app=my_app)
views文件下主要是蓝图,在__init__.py下导入并注册
二、将 Flask-Script 加入到Flask项目中
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import My_app 2 from flask_script import Manager 3 from flask_migrate import Migrate, MigrateCommand 4 from My_app import db 5 6 my_app = My_app.create_app() 7 # 让app支持 Manager 8 manage = Manager(my_app) 9 10 # Migrate 既然是数据库迁移,那么就得告诉他数据库在哪里 11 # 并且告诉他要支持那个app 12 Migrate(my_app, db) 13 # 现在就要告诉manager 有新的指令了,这个新指令在MigrateCommand 中存着呢 14 manage.add_command('databases', MigrateCommand) 15 16 17 @manage.command 18 def runflask(): 19 my_app.run() 20 return 'success' 21 22 23 @manage.option('-n', '--name', dest='name') 24 @manage.option('-s', '--say', dest='say') 25 def run_flask(name, say): 26 a = input("是否启动flask") 27 if a == 'y': 28 if not name: 29 name = '127.0.2.1' 30 if not say: 31 say = 5000 32 my_app.run(name, int(say)) 33 else: 34 return f"{name}真{say}" 35 36 37 if __name__ == '__main__': 38 manage.run()
三、运行 python manage.py databases init
之后会在目录下看到: