使用models目的是为了将创建数据库模型的代码与主程序代码分离,migrate的作用就是在数据库字段改变时不用drop表直接做更新操作
新建 models.py exts.py manage.py,程序入口 flask_test.py
manage.py
#-*-coding:utf-8-*- from flask_script import Manager
from flask_test import app #导入应用
#from db_script import db_manager
from flask_migrate import Migrate,MigrateCommand #导入migrate相关的模块
from exts import db #导入db对象
from models import * #从models导入数据库模型(数据库要创建的表) migrate = Migrate(app,db) #初始化migrate对象,绑定app应用和db manager = Manager(app) manager.add_command('dbupgrade',MigrateCommand) #把migratecommand命令添加到manager中,dbupgrade为自定义的名称 @manager.command
def runserver():
app.run(host='192.168.132.130',debug=True) manager.add_command('db',db_manager) if __name__ == '__main__':
manager.run()
exts.py
#-*-coding:utf-8-*-
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
models.py
#-*-coding:utf-8-*- 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(100),nullable=False)
password = db.Column(db.String(32),nullable=False ) class Article(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
title = db.Column(db.String(100),nullable=False)
content = db.Column(db.Text,nullable=False)
author_id = db.Column(db.Integer,db.ForeignKey('user.id')) author = db.relationship('User',backref=db.backref('articles'))
主程序文件flask_test.py
from flask import Flask,session
from exts import db
import config app = Flask(__name__)
app.config.from_object(config)
db.init_app(app) #数据库初始化当前app @app.route('/')
def index():
return 'Hello World!' if __name__ == '__main__':
app.run(host='192.168.132.130',debug=True)
migrate执行
注意:如果在次修改数据库模型,直接执行 migrate 后执行 upgrade即可