Posted by : at

Category : web-development   python   flask   sql

Setting up Flask Migrations

Migrations are needed for easy database changes, so that our data is not affected from any database changes

After setting up flask-sqlalchemy we can do database migrations, that makes the process alot user when shifting to a new database like sqlite, mysql or postgres. Also ensures that our data is safe.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

def hello_world():
    return jsonify({'Home': 'Hello World'})

if __name__ == "__main__":

We need to tell flask about our app, so that we can run the app using flask command

$ export

We will be using some Plugins for our database migrations

Install using pip

$ pip install Flask-Migrate
$ pip install Flask-Script

Now we need to config the managers in a for the migrations

from myapp import app, db
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
import os

MIGRATION_DIR = os.path.join('myapp', 'migrations')
migrate = Migrate(app, db, directory=MIGRATION_DIR)

manager = Manager(app)
manager.add_command('db', MigrateCommand)

## we need to add models for our database

class User(db.Model):
    __tablename__ = 'user'
    email = db.Column(db.String(100), unique=True, nullable=False)
    password = db.Column(db.String(8), nullable=False)

    def __init__(self, email, password): = email
        self.password = password

if __name__ == '__main__':

Now we need to initiate migrations using :

$ python db init

This will create all the folders required for migrations in your project folder.

Now we need to perform migrate operation ( its like staging or commiting before final changes)

$ python db migrate

To make the final changes to the database structure

$ python db upgrade

This will create all the necessary tables within your db