Migrations - Flask-Migrate (5) 总结

Overall Steps to Set Up & Run Migrations

  1. Bootstrap database migrate commands: link to the Flask app models and database, link to command line scripts for running migrations, set up folders to store migrations (as version of the database)
from flask import Flask, render_template, request, redirect, url_for, jsonify
from flask_sqlalchemy import SQLAlchemy
import sys
from flask_migrate import Migrate

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://username@localhost:5432/todoapp'
db = SQLAlchemy(app)

# Link to Flask app as well as the SQLAlchemy database
# migrate will do is start it up so that we can start using the Flask databae migrate commands to began initializing migrations
# and upgrading and downgrading and generating migrations as well.
migrate = Migrate(app, db)
# To set up the folders to store those migrations as versions of the database.
$ flask db init
  1. Run initial migration to create tables for SQLAlchemy models, recording the initial schema: ala git init && git commit. Replaces use of db.create_all()

  2. Migrate on changes to our data models

    • Make changes to the SQLAlchemy models
    • Allow Flask-Migrate to auto-generate a migration script based on the changes.
    • Fine-tune the migration scripts. For example, handle any existing data that we already had in our application.
    • Run the migration, aka “upgrade” the database schema by a “version”
$ flask db upgrade

猜你喜欢

转载自blog.csdn.net/BSCHN123/article/details/121398461