In this tutorial, we are going to see how to install Flask SQLAlchemy.

SQLAlchemy:

The SQLAlchamy is an object-relational mapper for ORM, it’s basically a database client. This kind of database client allows us to work on python classes and objects, and it automatically translates all the operations that we do with these into database instructions.

SQLAlchemy is a great package, one of the reasons is it supports several relational databases including the 3 most popular databases are SQLite, MYSQL and Postgress.

Flask SQLAlchemy:

The flask-sqlalchemy package provides a sqlalchemy wrapper that is friendly to flask applications.

Install Flask SQLAlchemy:

Install flask-sqlalchemy with the python package manager. Head over to the virtual environment and run the install command.

(venv) flask-tutorials % pip install flask-sqlalchemy 
Collecting flask-sqlalchemy
  Downloading Flask_SQLAlchemy-2.5.1-py2.py3-none-any.whl (17 kB)
Requirement already satisfied: Flask>=0.10 in ./venv/lib/python3.8/site-packages (from flask-sqlalchemy) (2.0.1)
Collecting SQLAlchemy>=0.8.0
  Downloading SQLAlchemy-1.4.21-cp38-cp38-macosx_10_14_x86_64.whl (1.5 MB)
     |████████████████████████████████| 1.5 MB 813 kB/s 
Requirement already satisfied: itsdangerous>=2.0 in ./venv/lib/python3.8/site-packages (from Flask>=0.10->flask-sqlalchemy) (2.0.1)
Requirement already satisfied: click>=7.1.2 in ./venv/lib/python3.8/site-packages (from Flask>=0.10->flask-sqlalchemy) (8.0.1)
Requirement already satisfied: Jinja2>=3.0 in ./venv/lib/python3.8/site-packages (from Flask>=0.10->flask-sqlalchemy) (3.0.1)
Requirement already satisfied: Werkzeug>=2.0 in ./venv/lib/python3.8/site-packages (from Flask>=0.10->flask-sqlalchemy) (2.0.1)
Collecting greenlet!=0.4.17; python_version >= "3"
  Downloading greenlet-1.1.0-cp38-cp38-macosx_10_14_x86_64.whl (87 kB)
     |████████████████████████████████| 87 kB 1.2 MB/s 
Requirement already satisfied: MarkupSafe>=2.0 in ./venv/lib/python3.8/site-packages (from Jinja2>=3.0->Flask>=0.10->flask-sqlalchemy) (2.0.1)
Installing collected packages: greenlet, SQLAlchemy, flask-sqlalchemy
Successfully installed SQLAlchemy-1.4.21 flask-sqlalchemy-2.5.1 greenlet-1.1.0

The flask-sqlalchemy comes with the inbuilt SQLite database, so do not worry about the local database server. After all, when we deploy the application into the production or any other major environments (DEV/QA), we can switch to MySQL or Postgress, etc., without making changes to our application.

Configure Flask SQLAlchemy:

To tell the flask-sqlalchemy the location of our database we need to use a configuration variable. It can be defined as a configuration variable in the flask, basically, it should be available in the flask app.config file.

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'

On the above config, I have taken the app.db where all DB related stuff is going to maintain.

In general, we used to define all our application configuration variables in a separate file called config.pyif you wish to do here you can freely define the database URI here also but make sure you have made this file to available to the flask app.config

import os

base_dir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
    SQLALCHEMY_DATABASE_URI = 'sqlite:///'+os.path.join(base_dir,'app.db')

Now let’s create a database instance in _init__.py>

from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object(Config) # Making sure Config class available to app configuration

db = SQLAlchemy(app)  # Creating SQLAlchemy object bypassing the app

from app import routes

Database Migrations:

The relational databases are very good at storing the structured content into the database. To make this happen we need to provide the structured database schema to the ORM. But the problem here is while developing, it happens to change the schema very frequently, so to make this transition simple, there are several good tools in the market that are dedicated to helping the transition schemas from one version to the next, these are called migration frameworks.

flask-migrateis a kind of framework that helps us to do the same migrations. So let’s install it.

(venv) flask-tutorials % pip install flask-migrate
Collecting flask-migrate
  Downloading Flask_Migrate-3.0.1-py2.py3-none-any.whl (12 kB)
Requirement already satisfied: Flask-SQLAlchemy>=1.0 in /Users/chandra/Work/MyWork/flask-tutorials/venv/lib/python3.8/site-packages (from flask-migrate) (2.5.1)
Collecting alembic>=0.7
  Downloading alembic-1.6.5-py2.py3-none-any.whl (164 kB)
     |████████████████████████████████| 164 kB 398 kB/s 
Requirement already satisfied: Flask>=0.9 in /Users/chandra/Work/MyWork/flask-tutorials/venv/lib/python3.8/site-packages (from flask-migrate) (2.0.1)
Requirement already satisfied: SQLAlchemy>=0.8.0 in /Users/chandra/Work/MyWork/flask-tutorials/venv/lib/python3.8/site-packages (from Flask-SQLAlchemy>=1.0->flask-migrate) (1.4.21)
Collecting Mako
  Downloading Mako-1.1.4-py2.py3-none-any.whl (75 kB)
     |████████████████████████████████| 75 kB 958 kB/s 
Collecting python-editor>=0.3
  Downloading python_editor-1.0.4-py3-none-any.whl (4.9 kB)
Collecting python-dateutil
  Downloading python_dateutil-2.8.2-py2.py3-none-any.whl (247 kB)
     |████████████████████████████████| 247 kB 2.0 MB/s 
Requirement already satisfied: itsdangerous>=2.0 in /Users/chandra/Work/MyWork/flask-tutorials/venv/lib/python3.8/site-packages (from Flask>=0.9->flask-migrate) (2.0.1)
Requirement already satisfied: Jinja2>=3.0 in /Users/chandra/Work/MyWork/flask-tutorials/venv/lib/python3.8/site-packages (from Flask>=0.9->flask-migrate) (3.0.1)
Requirement already satisfied: click>=7.1.2 in /Users/chandra/Work/MyWork/flask-tutorials/venv/lib/python3.8/site-packages (from Flask>=0.9->flask-migrate) (8.0.1)
Requirement already satisfied: Werkzeug>=2.0 in /Users/chandra/Work/MyWork/flask-tutorials/venv/lib/python3.8/site-packages (from Flask>=0.9->flask-migrate) (2.0.1)
Requirement already satisfied: greenlet!=0.4.17; python_version >= "3" in /Users/chandra/Work/MyWork/flask-tutorials/venv/lib/python3.8/site-packages (from SQLAlchemy>=0.8.0->Flask-SQLAlchemy>=1.0->flask-migrate) (1.1.0)
Requirement already satisfied: MarkupSafe>=0.9.2 in /Users/chandra/Work/MyWork/flask-tutorials/venv/lib/python3.8/site-packages (from Mako->alembic>=0.7->flask-migrate) (2.0.1)
Collecting six>=1.5
  Using cached six-1.16.0-py2.py3-none-any.whl (11 kB)
Installing collected packages: Mako, python-editor, six, python-dateutil, alembic, flask-migrate
Successfully installed Mako-1.1.4 alembic-1.6.5 flask-migrate-3.0.1 python-dateutil-2.8.2 python-editor-1.0.4 six-1.16.0

Integrate flask-mgrateextension with the application.

from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config.from_object(Config)

db = SQLAlchemy(app)
migrate = Migrate(app, db)

from app import routes, models

The Migrate class coming from falsk_migratepackage and it needs two arguments that are app and the db instance.

So far installation is good.

Now let’s create a simple User model and insert some data init.

from app import db

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)  # primary key column
    name = db.Column(db.String(32), index=True, unique=True) # creating indexed column and unique
    password = db.Column(db.String(32))

    def __repr__(self):
        return f'<User {self.name}>'

insert users init:

>>> from app.models import User
>>> u = User(name='chandra',password='123456'). # create User object
>>> u
<User chandra>

Done.

References:

Happy Learning:)

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment