app-generator / docs

App Generator - The Official Documentation | AppSeed
https://docs.appseed.us
1 stars 1 forks source link

Flask-Migrate #82

Open mahfujul-helios opened 8 months ago

mahfujul-helios commented 8 months ago

Flask-Migrate

Flask-Migrate is a Flask extension that provides support for database migrations in Flask applications. It integrates the Alembic migration framework with Flask, allowing developers to manage database schema changes and versioning seamlessly. Here's an overview of Flask-Migrate:

Features:

  1. Database Migrations: Flask-Migrate simplifies the process of managing database schema changes by generating and applying database migration scripts automatically. It tracks changes to the database schema over time and generates migration scripts that can be applied to update the database schema incrementally.

  2. Schema Versioning: Flask-Migrate maintains a version history of the database schema, allowing developers to track and manage changes to the database structure. It stores migration scripts in a version control system, making it easy to roll back changes or apply them to other instances of the application.

  3. Alembic Integration: Flask-Migrate is built on top of the Alembic migration framework, which provides powerful tools for generating and applying database migrations. It leverages Alembic's functionality to generate migration scripts based on changes to the application's SQLAlchemy models and apply those scripts to update the database schema.

  4. Command-Line Interface: Flask-Migrate provides a command-line interface (CLI) for managing database migrations from the terminal. Developers can use CLI commands to generate migration scripts, apply migrations, create and upgrade database versions, and perform other database-related tasks.

  5. Multiple Database Support: Flask-Migrate supports multiple database backends through SQLAlchemy, including SQLite, PostgreSQL, MySQL, and others. It provides a consistent interface for managing database migrations across different database engines, making it easy to deploy Flask applications in various environments.

  6. Integration with Flask-Script and Flask-CLI: Flask-Migrate integrates seamlessly with Flask-Script and Flask-CLI, two popular Flask extensions for managing command-line tasks. It provides commands for database migrations that can be easily integrated into Flask applications using these extensions.

  7. Customization: Flask-Migrate is highly customizable and extensible. Developers can customize the behavior of migration commands, configure database connection settings, specify migration directories, and implement custom migration scripts to handle complex database changes.

Advantages:

mahfujul-helios commented 7 months ago

Flask-Migrate

Flask migrate is defined as an extension that is used in the Flask application for handling database migrations for SQLAlchemy using Alembic. This module enables developers to quickly set up and starts the database schema migrations. The reason we require database migrations can be explained as follows. Suppose we build a database, and then require it to be modified by adding an extra column. Post addition we feel that the schema now present doesn’t fit well into the full application architecture and would like to return back to the original one. In a normal case it is difficult to do so, but with flask migrate the tasks are much smoother! In this article, we will look at ways on how we perform migration in Flask.

Syntax

Database migrations are the art of managing changes that are incremental, reversible, and controlled by version in the relational database schema. In the definition, we saw that we perform any migration when we feel the necessity to update into a newer version or even revert back to the older version. In this section, we will learn about migration in a flask from the syntax perspective so that when we learn about how to perform the migration, it is easier to map it back with the syntax learned here for a complete picture of the topic in discussion.

Installing flask migrate and configuring it:

pip install flask-migrate

Installing SQLAlchemy in Flask:

pip install flask-sqlalchemy

Configuring the Database URI in configuration parameter:

<Flaskapp variable >.config["SQLALCHEMY_DATABASE_URI"] = "< Link of the SQL Database

Initializing Migrate command:

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

Creation of migration repository:

flask db init

Creation of initial migration:

flask db migrate

How to perform migrate in Flask?

Before we think about performing migrate in Flask, we need to make sure that the module is installed in the python environment. For that, we would need to run the command pip install flask-migrate which will ensure that the module is installed in the environment where the python code will be running from. One needs to also make sure that the SQL alchemy module is also installed for smooth running of the migrate in Flask. Once everything is set, we are ready for the next steps in performing migrate in Flask.

Flask applications sometimes feel the necessity to dynamically using or insert their own settings in the Alembic configuration. For taking care of the utility, we use the decorator utility which uses the configure callback. Post the decorator utility and callback a function is defined. This function can modify the configuration object or completely replace it with the new variable within the function. Using decorator allows usage of multiple configuration callbacks and the order in which the callbacks are invoked are undetermined. Once the configuration piece is sorted, it would be time for binding the databases. The installation of the SQL alchemy module provides features to allow Flask-migrate to track migrations to multiple databases. This is possible with the binds feature of SQL alchemy. Including –multidb argument into the command enables the creation of multiple database migration repositories.

Now once the configurations and inclusion of arguments are taken care of, it is time for us to use the classes exposed by the module Flask migrate. This is to fill in all the settings in the python code to make sure that we proceed with the 3 migration commands. Before learning about using them for performing the migration in Flask, let us know about the classes individually. The classes which are exposed are Migrate and MigrateCommand. Migrate class itself covers all the functionality and utility of the extension whereas MigrateCommand is used when there is a need of exposing the database migration commands through the usage of the Flask script extension. Now to perform the next step of migrate, we would need to initialize the object and is done by command: Migrate(< Flask application variable >, < SQLAlchemy DB variable >). The 2 arguments that the Migrate class use is the application instance and the SQL alchemy database instance. Additional keywords are also taken which are the same that are passed to Alembic’s EnvironmentContext.configure() method. And finally, as a standard practice, Flask-migrate can be initialized using the init_app method. He other class which gets exposed to the user is MigrateCommand and once the initialization of Migrate is done, we need to declare an instance of Manager from the flask_script package by passing through it the application instance. Now that the manager object is instantiated, we would need to add a command to this object, and that will be MigrateCommnad.

The flow follows as:

from flask_script import Manager
from flask_migrate import MigrateCommand
appFlask = Flask(__name__)
manager = Manager(appFlask)
manager.add_command('< SQLAlchemy variable >', MigrateCommand)

Once the settings are done, we would proceed with the 3 migrations commands i.e. init, migrate and upgrade to perform the database migrations. The details of the database migrations are covered in another article in full detail.

Example #1

Installation of the Flask migrate module in Python environment:

Syntax:

pip install flask-migrate

Output:

migrate

Example #2

Initializing the migrate instance:

Syntax:

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

Output:

mi2

Example #3

Adding the MigrateCommand into the list of commands in the manager:

Syntax:

from flask_script import Manager
from flask_migrate import MigrateCommand
from flask import Flask
appFlask = Flask(__name__)
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(appFlask)
manager = Manager(appFlask)
manager.add_command('db', MigrateCommand)
manager

Output:

mi3

Conclusion In conclusion, in this article, we have learned about the migrate configuration and application in Flask. We can also use this methodology to include migration of an existing project as well so that developer doesn’t need to delete everything and then start from scratch. The only thing which needs to be kept in mind during the task of including migration in an existing project is some changes need to be made in the models of the source code. Like anytime else, rest is to you for experimentation.