Last modified: Jun 01, 2025 By Alexander Williams
Install Flask-SQLAlchemy in Python
Flask-SQLAlchemy is a Flask extension that simplifies database operations. It integrates SQLAlchemy with Flask for easy database management.
This guide will walk you through installing Flask-SQLAlchemy. You'll also learn basic usage with examples.
Table Of Contents
Prerequisites
Before installing Flask-SQLAlchemy, ensure you have:
- Python 3.6 or higher installed
- Basic knowledge of Flask framework
- Pip package manager
If you're new to Flask, check out our guide on How to Install Flask-Login in Python for related setup.
Installation Steps
Follow these simple steps to install Flask-SQLAlchemy:
1. Create a Virtual Environment
It's good practice to work in a virtual environment. This keeps your project dependencies isolated.
python -m venv myenv
source myenv/bin/activate # On Windows use: myenv\Scripts\activate
2. Install Flask-SQLAlchemy
With your environment activated, install the package using pip:
pip install flask-sqlalchemy
This will install both Flask and SQLAlchemy as dependencies.
3. Verify Installation
Check if the installation was successful:
pip show flask-sqlalchemy
You should see package information if installed correctly.
Basic Usage Example
Here's a simple Flask application using Flask-SQLAlchemy:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
@app.route('/')
def home():
return "Flask-SQLAlchemy is working!"
if __name__ == '__main__':
app.run(debug=True)
This code creates a basic Flask app with SQLite database. The User
model defines a simple table structure.
Database Operations
Flask-SQLAlchemy makes database operations simple. Here are common tasks:
Create Tables
To create all defined tables, use:
with app.app_context():
db.create_all()
This creates the database file and tables. The file will be in your project directory.
Add Records
Adding new records is straightforward:
new_user = User(username='john_doe')
db.session.add(new_user)
db.session.commit()
Remember to always commit your changes to save them.
Query Records
Retrieve data using simple queries:
users = User.query.all() # Get all users
user = User.query.filter_by(username='john_doe').first()
Configuration Options
Flask-SQLAlchemy offers several configuration options:
SQLALCHEMY_DATABASE_URI
: Database connection stringSQLALCHEMY_TRACK_MODIFICATIONS
: Set to False to disable trackingSQLALCHEMY_ECHO
: Set to True for SQL query logging
For more advanced database operations, consider learning about Flask-Migrate for database migrations.
Common Issues
Here are some common problems and solutions:
Database URI Not Set
Always set SQLALCHEMY_DATABASE_URI
before creating SQLAlchemy instance.
Context Errors
Database operations need application context. Use with app.app_context()
when working outside routes.
Session Management
Remember to commit()
after changes and rollback()
on errors.
Conclusion
Flask-SQLAlchemy simplifies database operations in Flask applications. It provides an intuitive interface to SQLAlchemy.
With this guide, you've learned to install and use Flask-SQLAlchemy. For form handling, check our guide on Installing Flask-WTF.
Start building your Flask applications with powerful database support today!