flask-模型

模型简单使用

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://root:root@127.0.0.1:3306/xxx"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)

Migrate(app, 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)
    age = db.Column(db.INTEGER, nullable=False)


manage = Manager(app)
manage.add_command("db", MigrateCommand)
if __name__ == '__main__':
    manage.run()

运行数据库命令

# 初始化
python app.py db init
# 生成迁移文件
python app.py db migrate
# 执行迁移命令
python app.py db upgrade   

manage的用法

from flask import Flask
from flask_script import Manager

manage = Manager(app=Flask(__name__))


@manage.command
def hello():
    print("hello")


@manage.option("-u", "--username", dest="name")
def test(name):
    print("name是%s" % name)


if __name__ == '__main__':
    manage.run()
python app.py greet 
# 这个命令会执行greet函数
python app.py test -u xxxx
# 这个命令会将xxxx参数传递到name变量
posted @ 2020-07-31 11:59  huameixiao  阅读(120)  评论(0编辑  收藏  举报