flask 與 flask_migrate的使用

flask 與 flask_migrate的使用

1、安裝

pip install Flask-Migrate

2、簡單使用

# 文件:manage.py

from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask import Flask

DBUser = "root"
DBPwd = "root"
DBName = "flask_db_1"
DBHost = "127.0.0.1"
DBPort = 3306

database_url = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(
    DBUser, DBPwd, DBHost, DBPort, DBName)

app = Flask(__name__)

app.config["SQLALCHEMY_DATABASE_URI"] = database_url
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy()
migrate = Migrate()

migrate.init_app(app=app, db=db)
db.init_app(app)


class User(db.Model):
    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    name = db.Column(db.String(32))


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

3、經過終端進行數據庫遷移操做

首先進入該文件的目錄下python

相應執行下面的命令mysql

set FLASK_APP=manage.py
flask db init
flask db migrate
flask db upgrade

執行完畢以後,你再去數據庫中查看,新建加了一些表,其中就是user表sql

相關文章
相關標籤/搜索