0
0
Flaskframework~5 mins

Repository pattern for data access in Flask

Choose your learning style9 modes available
Introduction

The repository pattern helps organize how your app talks to the database. It keeps data access code separate and easy to manage.

When you want to keep your database code clean and separate from your app logic.
When you plan to change the database later and want to avoid rewriting lots of code.
When you want to write tests without needing a real database.
When multiple parts of your app need to access data in a consistent way.
Syntax
Flask
class Repository:
    def __init__(self, db_session):
        self.db_session = db_session

    def add(self, entity):
        self.db_session.add(entity)
        self.db_session.commit()

    def get(self, entity_id):
        return self.db_session.query(Entity).get(entity_id)

    def list(self):
        return self.db_session.query(Entity).all()

The Repository class wraps database operations.

Use methods like add, get, and list to work with data.

Examples
This example shows a repository for users, with methods to add and get users.
Flask
class UserRepository:
    def __init__(self, db_session):
        self.db_session = db_session

    def add_user(self, user):
        self.db_session.add(user)
        self.db_session.commit()

    def get_user(self, user_id):
        return self.db_session.query(User).get(user_id)
This example lists all products using the repository pattern.
Flask
class ProductRepository:
    def __init__(self, db_session):
        self.db_session = db_session

    def list_products(self):
        return self.db_session.query(Product).all()
Sample Program

This Flask app uses SQLAlchemy and the repository pattern to add and list users. It keeps database code inside UserRepository.

Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

class UserRepository:
    def __init__(self, db_session):
        self.db_session = db_session

    def add_user(self, user):
        self.db_session.add(user)
        self.db_session.commit()

    def get_user(self, user_id):
        return self.db_session.query(User).get(user_id)

    def list_users(self):
        return self.db_session.query(User).all()

with app.app_context():
    db.create_all()
    repo = UserRepository(db.session)

    user1 = User(name='Alice')
    user2 = User(name='Bob')

    repo.add_user(user1)
    repo.add_user(user2)

    all_users = repo.list_users()
    for user in all_users:
        print(f'User {user.id}: {user.name}')
OutputSuccess
Important Notes

Using the repository pattern makes your code easier to test and maintain.

Remember to commit changes in the repository methods to save data.

Keep repository methods focused on one task for clarity.

Summary

The repository pattern separates data access from app logic.

It helps keep your code clean and easier to change later.

Use repository classes to add, get, and list data in a simple way.