Yesterday I covered forms with Flask-WTF. Today, for day 82, it was about adding a real database. In Django, this was built in. In Flask, you bring it in yourself with Flask-SQLAlchemy for the ORM and Flask-Migrate for migrations. The concepts are identical to Django; the setup is just more manual.
What is Flask-SQLAlchemy?
SQLAlchemy is Python's most popular ORM. It works with PostgreSQL, MySQL, SQLite, and more. Flask-SQLAlchemy is a Flask extension that integrates SQLAlchemy cleanly into Flask apps, handling the database connection and session management for you.
pip install flask-sqlalchemy flask-migrate
Enter fullscreen mode
Exit fullscreen mode
Two packages:
flask-sqlalchemy — the ORM itself
flask-migrate — handles database migrations, built on top of Alembic
Setup
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate
app = Flask ( __name__ ) app . config [ ' SECRET_KEY ' ] = ' your-secret-key ' app .…