MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Flask-SQLAlchemy Setup & Engine Configuration0%
Study Materials
FlaskProgress 0%
1.1What is Flask & WSGI Architecture1.2Virtual Environments & First Flask Application1.3Flask CLI & Environment Configuration
5.1Flask-SQLAlchemy Setup & Engine Configuration5.2Defining Models & Column Constraints5.3Database Relationships (One-to-Many & Many-to-Many)5.4CRUD Operations, Query Filtering & Pagination5.5Database Schema Migrations with Flask-Migrate
HomeTutorialsFlaskFlask-SQLAlchemy Setup & Engine Configuration
Defining Models & Column Constraints

Flask-SQLAlchemy Setup & Engine Configuration

Beginner12 min read•Updated: 2026-09-16•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Persistent data storage is the backbone of web applications. While Python supports raw database drivers (like sqlite3 or psycopg2), writing raw SQL strings is tedious, error-prone, and vulnerable to SQL injection.

Flask-SQLAlchemy integrates SQLAlchemy—the premier Object Relational Mapper (ORM) for Python—with Flask. It manages database engines, handles connection pooling, and simplifies session lifecycles.


1. Installing Flask-SQLAlchemy 3.x

Install the extension:

1pip install flask-sqlalchemy

For PostgreSQL or MySQL support, install the corresponding database driver:

1# For PostgreSQL
2pip install psycopg2-binary
3 
4# For MySQL
5pip install pymysql

2. Configuring the Database URI

Flask-SQLAlchemy connects to your database via SQLALCHEMY_DATABASE_URI. The URI format follows standard RFC connection strings:

1dialect+driver://username:password@host:port/database_name

Common Database URI Formats:

Database EngineSQLALCHEMY_DATABASE_URI Example
SQLite (Local File)sqlite:///app.db (relative to instance folder)
SQLite (In-Memory for Tests)sqlite:///:memory:
PostgreSQLpostgresql+psycopg2://db_user:secret_pass@localhost:5432/msk_db
MySQL / MariaDBmysql+pymysql://db_user:secret_pass@localhost:3306/msk_db

3. Initializing the SQLAlchemy Extension

In modern Flask-SQLAlchemy 3.x, initialize the SQLAlchemy object and bind it to your application:

1import os
2from flask import Flask
3from flask_sqlalchemy import SQLAlchemy
4 
5app = Flask(__name__)
6 
7# Configure local SQLite database inside Flask's secure instance/ folder
8basedir = os.path.abspath(os.path.dirname(__file__))
9app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join(basedir, "instance", "app.db")
10app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
11 
12# Production Connection Pool Tuning (PostgreSQL / MySQL)
13app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {
14 "pool_size": 10, # Maximum number of permanent connections
15 "max_overflow": 20, # Extra connections created during traffic surges
16 "pool_timeout": 30, # Seconds to wait before timing out
17 "pool_recycle": 1800 # Recycle connections every 30 minutes to prevent disconnects
18}
19 
20# Instantiate the ORM extension
21db = SQLAlchemy(app)

4. Understanding Application Context and db.create_all()

In Flask-SQLAlchemy 3.x, database operations (like creating tables) must run within Flask's application context:

1# Create database tables defined by your models
2with app.app_context():
3 db.create_all()
4 print("Database tables initialized successfully!")

Attempting to run db.create_all() outside with app.app_context(): will raise an ActiveContextError or RuntimeError: Working outside of application context.


Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What configuration key specifies the database connection string in Flask-SQLAlchemy?
Question 2
Why should SQLALCHEMY_TRACK_MODIFICATIONS be explicitly set to False?
Question 3
Why must db.create_all() be executed inside with app.app_context(): in Flask-SQLAlchemy 3.x?
Question 4
What does the SQLite URI sqlite:///app.db (with three slashes) denote?
Question 5
What is the purpose of pool_recycle in SQLALCHEMY_ENGINE_OPTIONS?
Next Lesson

Defining Models & Column Constraints

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Flash Messaging System & User Feedback UIDefining Models & Column Constraints

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Flask with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext