flask
  1. flask-sqlalchemy

SQLAlchemy - Database Integration in Flask

Syntax

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/db_name'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

Example

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:password@localhost/mydb'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    email = db.Column(db.String(100), unique=True, nullable=False)
    password = db.Column(db.String(100), nullable=False)

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

db.create_all()

Output

CREATE TABLE user (
        id INTEGER NOT NULL,
        name VARCHAR(50) NOT NULL,
        email VARCHAR(100) NOT NULL,
        password VARCHAR(100) NOT NULL,
        PRIMARY KEY (id),
        UNIQUE (email)
)

Explanation

SQLite is the default database for Flask applications. SQLAlchemy is a toolkit that provides SQL support to your Flask application. The flask_sqlalchemy extension provides a set of tools for working with SQLAlchemy database.

Use

In order to use SQLAlchemy with Flask, you need to install both Flask and SQLAlchemy. Next, you need to specify URI of your database and configure the connection to the database. You can then create classes which inherit from db.Model and represent tables in your database.

Important Points

  • SQLAlchemy is a toolkit that provides SQL support to your Flask application
  • The flask_sqlalchemy extension provides a set of tools for working with SQLAlchemy database
  • To use SQLAlchemy with Flask, you need to install both Flask and SQLAlchemy
  • You need to specify the URI of your database and configure the connection to the database
  • You can create classes which inherit from db.Model and represent tables in your database

Summary

In this page, we learned about integrating SQLAlchemy with Flask. SQLAlchemy is a toolkit that provides SQL support to your Flask application. The flask_sqlalchemy extension provides a set of tools for working with SQLAlchemy database. We also saw an example of creating a User class that represents a table in a MySQL database.

Published on: