Introduction

Flask-SQLAlchemy is an extension for Flask that simplifies database integration by providing an easy-to-use interface for working with SQL databases. In this guide, we'll explore how to work with Flask-SQLAlchemy, including setting up a database, defining models, creating tables, and performing database operations in your Flask application.


Step 1: Setting Up Your Flask Application

Start by setting up your Flask application and installing Flask-SQLAlchemy. Create a virtual environment and initialize your application. Here's a sample directory structure:

my-sqlalchemy-app/
app.py

Step 2: Configuring Flask-SQLAlchemy

Configure Flask-SQLAlchemy by providing your database connection string. Here's an example configuration in your Flask app:

# app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db'
db = SQLAlchemy(app)

Step 3: Defining Models

Create models for your database tables. Models define the structure of your data. Here's an example model for a "User" table:

# app.py
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __init__(self, username, email):
self.username = username
self.email = email

Step 4: Creating Database Tables

Create the database tables by running the `create_all()` method. This initializes the database schema based on your defined models:

# app.py
with app.app_context():
db.create_all()

Step 5: Performing Database Operations

You can perform various database operations using Flask-SQLAlchemy, including querying, adding, updating, and deleting records. Here's an example of adding a new user to the "User" table:

# app.py
new_user = User(username='john_doe', email='john@example.com')
db.session.add(new_user)
db.session.commit()

Conclusion

Working with Flask-SQLAlchemy simplifies database integration in Flask applications. By following the steps in this guide, you can set up a database, define models, create tables, and perform various database operations seamlessly. Flask-SQLAlchemy is a powerful tool for managing data and databases in your Flask application.