EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Flask Tutorial Flask DB Migrate
Secondary Sidebar
Flask Tutorial
  • Flask
    • Flask Version
    • Flask make_response
    • Flask WebSocket
    • Flask Session
    • Flask Environment Variables
    • Flask Cache
    • Flask Server
    • Flask jsonify
    • Flask logging
    • Flask redirect
    • Flask wtforms
    • Flask config
    • Flask Users
    • Flask upload file
    • Flask? get post data
    • Flask Template
    • Flask DB Migrate
    • Flask HTTPS
    • Flask bcrypt
    • Flask debug mode
    • Flask authentication
    • Flask Migrate
    • Flask URL Parameters
    • Flask API
    • Flask bootstrap
    • Flask POST request
    • Flask Extensions

Flask DB Migrate

By Alokananda GhoshalAlokananda Ghoshal

Flask DB Migrate

Definition of Flask DB Migrate

Flask DB migrate is defined as a flask extension that enables developers to handle migrations of SQLAlchemy DB-based Flask application. This utility is possible through a tool known as Alembic. Alembic is a database migration tool that is written by the author of SQLAlchemy and provides various functions that are a part of Alembic, like emitting ALTER statements for changing the structure of a table, providing a system for migration scripts to be constructed, and allowing scripts to run in a chronological manner. One can perform the database operations through Flask command-line interface or can use the flask script extension. Let’s find out in this article how do we start migrations when an application already has an established database!

Syntax:

Now in this section, we will look at syntax before we jump on to understanding the working of DB migrate and the reason we do that is that having a superficial understanding of syntax will enable easy grasping of the entire context of make response:

Installing flask migrate and configuring it:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

pip install flask-migrate

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,697 ratings)

Options in flask db help

flask db --help

Instantiating the migrate instance in a Flask application:

migrate = Migrate(<Flask application variable>, <SQLAlchemy variable>

Creation of migration repository:

flask db init

Creation of initial migration:

flask db migrate

How does DB migrate work in Flask?

Before we talk about DB migrations in Flask, we should be aware of SQLAlchemy in Flask. Let us run through a short introduction about SQLAlchemy and then knowing about migration will be a cakewalk. The most important fundamental about SQLAlchemy is to know how we can CREATE tables db.create_all. This utility helps in issuing CREATE statements for the table object and closely connect it to related constructs. The create_all utility function is issued on the MetaData object and it checks if a table exists and if not the CREATE statements are issued to build that table.

In knowing how much effort it might take to assign CREATE statements to build a table, it might be a viable solution in case one individual is working on building a solution but in terms of scaling this process might be very cumbersome and hence inefficient to scale and maintain. This is where role of migrations comes to play and can be thought about as a very similar concept of git, which can be applied to the changes to the database. Any DDL that is written in order to change the structure, we must make everyone fully aware of the change so that necessary actions can be taken by respective people and that these changes are permanent in nature.

Flask DB migrations are those files that run to execute SQL and perform DDL on the schema and to assist developers, we would need to use flask-migrate. Now to run flask-migrate effectively we would need to know the working of 3 magic migration commands which will overall complete the story of working of DB migrate, though there are a lot of other commands one would have access to!

The first command is init. This code is run in order to set up the migration directory. In this command, a migration repository is created and in due course of actions to perform the task, a couple of folders are created in the root where the migrations will be stored. Just drawing the same analogy of git, we would need to flask db init once, to keep everything ready!

Now that everything is ready with init, we would need to start off by creating pending migrations on the basis of the model’s look by using migrate command. Here, a python file is created inside the path /migrations/versions enabling developers running SQL for making modifications to the schema based on the Model. The name that will be created for the name is randomly generated and if one needs to have a human-readable format for the file, -m flag needs to be used to ensure we have a human-readable filename.

The final nail is to use an upgrade to run the pending migrations that were created by migrate command on the basis of the Model and made sure that those are run to make a change to the schema. When we run a migrate command, we would generally be given a choice of upgrade or downgrade, carefully choosing of which can make you move ahead in the migration history (upgrade) or move back in migration history (downgrade). With the complete run of migration, a row is added to the alembic_version table of the database with id of the migration that happened! With this, we now know the full cycle working of DB migrate and now it turns to look at some examples!

Examples

In the below examples we will look at how to instantiate a DB migrate instance using command-line interface, post which we will look at options available with the flask DB command. and then take one step deeper using the init command followed by the migrate command. Upgrade command is left to the user to try and experiment!

Example #1

Installing flask migrate and configuring it

Syntax:

pip install flask-migrate

Output:

example 1

Example #2

Instantiating the migrate instance in a Flask application

Syntax:

from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask import Flask
appFlask = Flask(__name__)
db = SQLAlchemy(appFlask)
db

Output:

flask db migrate 1

Example #3

Options in flask db help:

Syntax:

flask db --help

Output:

flask db migrate 2

Example #4

Creation of initial migration

Syntax:

flask db init

Output:

example 4

Example #5

Creation of initial migration

Syntax:

flask db migrate

Output:

example 5

Conclusion

In this article, we have got to know about the full details of how DB migrate works in Flask and what are the main components which are responsible for DB migration to work. We have also looked at some of the applications through hands-on visualization and experiment. The upgrade option of DB is left to the readers to try it out and observe the steps in the output for an end-to-end learning!

Recommended Articles

This is a guide to Flask DB Migrate. Here we discuss the definition, How does DB migrate work in Flask? examples with code implementation respectively. You may also have a look at the following articles to learn more –

  1. Django vs Flask
  2. Python mkdir
  3. Python Virtualenv
  4. Python AssertionError
Popular Course in this category
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)
  41 Online Courses |  13 Hands-on Projects |  322+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more