大家好,我是天空之城,今天帶來小福利,flask架構學習筆記(11)–Flask資料庫
flask資料庫的遷移和生成
項目總圖
首先通過cmd視窗進入到項目所在檔案夾,
建立虛拟環境pipenv shell(要先安裝pip install pipenv包)
執行flask資料庫遷移的三個步驟
python manage.py db init初始化
python manage.py db migrate
python manage.py db upgrade
最後可以檢視到資料庫裡建立了User表格
manage.py檔案
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from exts import db
from flask_app import app
# 需要映射那個模型到資料庫,我們就導入哪個
from models import User
manage = Manager(app)
Migrate(app, db)
manage.add_command('db', MigrateCommand)
# @manage.option('-n', dest='name')
# @manage.option('-e', dest='email')
# @manage.option('-p', dest='password')
# @manage.option('-a', dest='age')
# def add_user(name, email, password, age):
# user = User(name=name, email=email, password=password, age=age)
# db.session.add(user)
# db.session.commit()
if __name__ == '__main__':
manage.run()
flask_app檔案
from flask import Flask
import config
from models import User
from exts import db
app = Flask(__name__)
app.config.from_object(config)
# db = SQLAlchemy(app)
db.init_app(app)
# user = User(name='cheney', email='[email protected]', password='123')
# db.session.add(user)
# db.session.commit()
@app.route('/')
def index():
return '這是首頁'
if __name__ == '__main__':
app.run(debug=True)
models.py檔案 建表檔案
from exts import db
class User(db.Model):
__tablename__ = 'project_user'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(50))
email = db.Column(db.String(50))
password = db.Column(db.String(50))
age = db.Column(db.Integer)
# db.create_all()
exts.py檔案
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
config.py檔案
HOSTNAME = '127.0.0.1'
# 資料庫
# 幾棟
DATABASE = 'demo'
# 端口
# 門牌号
PORT = 3306
# 使用者名和密碼
# 鑰匙
USERNAME = 'root'
PASSWORD = 'root'
DB_URL = 'mysql+pymysql://{}:{}@{}:{}/{}'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
SQLALCHEMY_DATABASE_URI = DB_URL
SQLALCHEMY_TRACK_MODIFICATIONS = False