How to Use SQLAlchemy with Flask for Database Management

 ๐Ÿ—ƒ️ How to Use SQLAlchemy with Flask for Database Management

SQLAlchemy is a powerful Python ORM (Object Relational Mapper) that integrates seamlessly with Flask. It allows you to interact with your database using Python classes instead of raw SQL.


๐Ÿ”ง 1. Install Flask and SQLAlchemy

You can install both using pip:


bash

Copy

Edit

pip install Flask SQLAlchemy

If you're planning to use a virtual environment (recommended):


bash

Copy

Edit

python -m venv venv

source venv/bin/activate  # On Windows: venv\Scripts\activate

pip install Flask SQLAlchemy

๐Ÿ“ 2. Basic Project Structure

arduino

Copy

Edit

/flask_app

  ├── app.py

  ├── models.py

  ├── config.py

  └── requirements.txt

⚙️ 3. Configuration Setup

config.py

python

Copy

Edit

import os


BASE_DIR = os.path.abspath(os.path.dirname(__file__))


class Config:

    SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASE_DIR, 'app.db')

    SQLALCHEMY_TRACK_MODIFICATIONS = False

๐Ÿš€ 4. Initialize Flask and SQLAlchemy

app.py

python

Copy

Edit

from flask import Flask

from flask_sqlalchemy import SQLAlchemy

from config import Config


app = Flask(__name__)

app.config.from_object(Config)


db = SQLAlchemy(app)


# Import models after db is initialized

from models import User


@app.route('/')

def index():

    return "Hello, Flask with SQLAlchemy!"


if __name__ == '__main__':

    app.run(debug=True)

๐Ÿงฑ 5. Define Your Database Models

models.py

python

Copy

Edit

from app import db


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 __repr__(self):

        return f'<User {self.username}>'

๐Ÿ› ️ 6. Create the Database and Tables

Run Python in the shell or create a script:


bash

Copy

Edit

python

python

Copy

Edit

from app import db

db.create_all()

exit()

This will create a file called app.db with the tables defined in your models.


✍️ 7. Add and Query Data

Example shell usage:


python

Copy

Edit

from app import db

from models import User


# Create a user

new_user = User(username="john", email="john@example.com")

db.session.add(new_user)

db.session.commit()


# Query users

users = User.query.all()

print(users)


# Filter

john = User.query.filter_by(username="john").first()

print(john.email)

✅ 8. Best Practices

Use Flask-Migrate for migrations (pip install flask-migrate)


Structure your app using Blueprints for larger projects


Set environment variables for DB credentials in production


๐Ÿ“ฆ 9. Using Flask-Migrate (Optional but Recommended)

To manage database schema changes easily:


bash

Copy

Edit

pip install Flask-Migrate

In app.py:


python

Copy

Edit

from flask_migrate import Migrate

migrate = Migrate(app, db)

Then run:


bash

Copy

Edit

flask db init

flask db migrate -m "Initial migration"

flask db upgrade

๐ŸŽฏ Conclusion

With Flask and SQLAlchemy, you can:


✅ Define models with Python classes

✅ Interact with databases using ORM

✅ Manage migrations with Flask-Migrate

✅ Build full-featured apps with clean database integration

Learn Full Stack Python Course in Hyderabad

Read More

Introduction to MongoDB for Full Stack Python

Creating and Managing Relationships in Databases with Django ORM

Implementing Authentication with Databases in Python

Using Django ORM to Interact with Databases

Visit Our Quality Thought Training in Hyderabad

Get Directions

Comments

Popular posts from this blog

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Installing Tosca: Step-by-Step Guide for Beginners

Why Data Science Course?