Flask Migrations using Flask-SQLAlchemy

Subscribe to my newsletter and never miss my upcoming articles

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.

run.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)

@app.route('/')
def hello_world():
    return jsonify({'Home': 'Hello World'})


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

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

$ export FLASK_APP=run.py

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 manage.py for the migrations

manage.py

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


app.config.from_object('YOUR_APPLICATION_ENV_VARIABLE')
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):
        self.email = email
        self.password = password


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

Now we need to initiate migrations using :

$ python manage.py 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 manage.py db migrate

To make the final changes to the database structure

$ python manage.py db upgrade

This will create all the necessary tables within your db.

No Comments Yet