flask框架資料庫遷移
阿新 • • 發佈:2018-12-10
前言
需要匯入
from flask import Flask
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
示例
# -*- coding:utf-8 -*- from flask import Flask, render_template, url_for, request, redirect from flask_sqlalchemy import SQLAlchemy from flask_wtf import Form from wtforms import StringField, SubmitField from wtforms.validators import DataRequired from flask_script import Manager from flask_migrate import Migrate, MigrateCommand app = Flask(__name__) # 配置引數 class Config(object): """配置引數""" # sqlalchemy的配置引數 SQLALCHEMY_DATABASE_URI = "mysql://root:
[email protected]:3306/db_ab" # 設定sqlalchemy自動跟蹤資料庫 SQLALCHEMY_TRACE_MODIFICATIONS = True # 設定祕鑰 SECRET_KEY = "ABCDEFG1234567" app.config.from_object(Config) db = SQLAlchemy(app) manager = Manager(app) # 建立flask指令碼管理物件 Migrate(app, db) # 建立資料庫遷移工具物件 manager.add_command("db", MigrateCommand) # 向manager中新增資料庫遷移工具 # 資料庫遷移操作 # 1、初始化 # python authorbook.py db init # 2、遷移(帶註釋) # python authorbook.py db migrate -m "add email" # 3、遷移後更新 # python authorbook.py db upgrade # 檢視遷移歷史 # python authorbook.py db history # 降級到遷移(狀態碼為455b9cced7b) # python authorbook.py db downgrade 455b9cced7b # 資料庫模型 class Author(db.Model): """作者""" __tablename__ = "tbl_authors" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32)) books = db.relationship("Book", backref="author") # email = db.Column(db.String(32)) class Book(db.Model): """書籍""" __tablename__ = "tbl_books" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) author_id = db.Column(db.Integer, db.ForeignKey("tbl_authors.id")) # 表單模型 class AuthorBookForm(Form): """表單模型""" author_name = StringField(label=u"作者", validators=[DataRequired(u"作者不能為空!")]) book_name = StringField(label=u"書籍", validators=[DataRequired(u"書籍不能為空!")]) submit = SubmitField(label=u"儲存") @app.route("/", methods=["GET", "POST"]) def index(): # 提交表單資料 form = AuthorBookForm() if form.validate_on_submit(): # 表單資料通過驗證 # 獲取表單資料 author_name = form.author_name.data book_name = form.book_name.data # 儲存到資料庫 author = Author(name=author_name) db.session.add(author) db.session.commit() book = Book(name=book_name, author_id=author.id) db.session.add(book) db.session.commit() # 查詢作者 author_li = Author.query.all() return render_template("author_book.html", authors=author_li, form=form) @app.route("/delete_book", methods=["GET"]) def delete_book(): # 獲取引數 book_id = request.args.get("book_id") # 刪除資料 book = Book.query.get(book_id) db.session.delete(book) db.session.commit() return redirect(url_for("index")) if __name__ == "__main__": manager.run()
Step1初始化
初始化後將在工作目錄下生成一個migrates資料夾