使用Flask-migrate迁移数据库
1.安装:
pip install flask-migrate
2.主要命令
python manager.py db init
python manager.py db migrate
python manager.py db upgrade
3.应用实例
数据库:MySql
数据库名称:db_cms
连接账号:root
连接口令:123456
模型文件,分前后端,前端一个,后端一个,admin\models.py、front\models.py
4.文件介绍
项目结构:
config.py
#encoding:utf-8 import os ADMIN_USER_ID = 'XXX' MEMBER_USER_ID='XXX' SECRET_KEY = os.urandom(24) DEBUG=True DB_USERNAME = 'root' DB_PASSWORD = '123456' DB_HOST = '127.0.0.1' DB_PORT = '3306' DB_NAME = 'db_cms' DB_URI = 'mysql+pymysql://%s:%s@%s:%s/%s?charset=utf8' % (DB_USERNAME,DB_PASSWORD,DB_HOST,DB_PORT,DB_NAME) SQLALCHEMY_DATABASE_URI = DB_URI SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_ECHO= False WTF_CSRF_ENABLED = False#关闭CSRF保护 #上传到本地 UEDITOR_UPLOAD_PATH = os.path.join(os.path.dirname(__file__),'static','images')
exts.py
#encoding:utf-8 from flask_sqlalchemy import SQLAlchemy db=SQLAlchemy()
app.py
from flask import Flask from apps.admin import bp as admin_bp#导入各个模块app from apps.front import bp as front_bp from apps.common import bp as common_bp from apps.ueditor import bp as edtior_bp from flask_wtf import CSRFProtect as WTF # 利用表单类去渲染模板时需要用到 from exts import db def create_app(): app = Flask(__name__) #注册蓝图 app.register_blueprint(admin_bp) app.register_blueprint(front_bp) app.register_blueprint(common_bp) app.register_blueprint(edtior_bp) app.config.from_object('config')#使用模块的名字 #WTF(app) db.init_app(app) return app if __name__ == '__main__': app=create_app() app.run(host='127.0.0.1', port=8000, debug=True)
manager.py
from flask_script import Manager from flask_migrate import Migrate,MigrateCommand from app import create_app from exts import db from apps.admin import models as admin_models app=create_app() manager=Manager(app) Migrate(app,db) manager.add_command('db',MigrateCommand) @manager.option('-u', '--username', dest='username') @manager.option('-p', '--password', dest='password') @manager.option('-e', '--email', dest='email') def create_user(username,password,email): user=admin_models.Users(username=username,password=password,email=email) db.session.add(user) db.session.commit() print("用户添加成功!") if __name__=='__main__': manager.run()
apps\admin\models.py,只是截取其中的一部分,一个数据模型
#encoding:utf-8 from exts import db from datetime import datetime from werkzeug.security import generate_password_hash,check_password_hash from sqlalchemy.orm import relationship #创建关系 class Users(db.Model): __tablename__='tbuser' uid=db.Column(db.Integer,primary_key=True,autoincrement=True) username=db.Column(db.String(50),nullable=False,unique=True)#用户名不能为空,而且必须是唯一的 _password = db.Column(db.String(100), nullable=False) # 密码不能为空 email=db.Column(db.String(50),nullable=False,unique=True)#用户邮箱不能为空,而且必须是唯一的 sex=db.Column(db.String(2),default=0)#性别 telephone=db.Column(db.String(11))#电话 status=db.Column(db.Integer)#状态 is_super = db.Column(db.SmallInteger) # 是否为管理员,1为管理员 remarks=db.Column(db.String(500))#备注 reg_time=db.Column(db.DateTime,default=datetime.now) def __init__(self,username,password,email): self.username=username self.password=password self.email=email
apps\front\models.py
#encoding:utf-8 from exts import db from datetime import datetime from werkzeug.security import generate_password_hash,check_password_hash class Members(db.Model): __tablename__ = 'tbmember' uid = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(50), nullable=False, unique=True) _password = db.Column(db.String(100), nullable=False) email = db.Column(db.String(50), nullable=False, unique=True) vatar=db.Column(db.String(80),nullable=True) nickname=db.Column(db.String(50),nullable=True) sex = db.Column(db.String(2), default=0) telephone = db.Column(db.String(11)) status = db.Column(db.Integer) def __init__(self,username,password,email): self.username=username self.password=password self.email=email
上面apps\admin\models.py和apps\front\models.py,都是只截取模型的一部分,在实际工程实践中,分别增加前后端的模型
5.操作步骤
1)、启动mysql,建立数据库db_cms
2)、检查与更改config.py,确认数据库名是db_cms
3)、从命令行进入项目文件夹,cd ..\cms,启动虚拟环境
(Flask_Venv)C:\xxx\cms>
4)、执行命令:python manager.py db init 则在项目中生成文件夹migrations
执行命令:python manager.py db migrate 生成迁移文件,迁移文件存放在migrations\versions下面
执行命令:python manager.py db upgrade 把生成的迁移文件里的数据模型,在mysql数据库里生成相应的表
5)、执行命令:python manager.py create_user -u admin -p 123456 -e abc@qq.com
调用manager.py里的create_user函数,向数据库db_cms的tbUser表里插入一条记录,username 为admin,口令为123456,邮箱为abc@qq.com
此调用,会触发apps\admin\models.py里下面语句,如果二者参数不一致,会报错。
def __init__(self,username,password,email): self.username=username self.password=password self.email=email