Skip to content

Instantly share code, notes, and snippets.

@dhrrgn
Last active March 2, 2022 04:16
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhrrgn/5936552 to your computer and use it in GitHub Desktop.
Save dhrrgn/5936552 to your computer and use it in GitHub Desktop.
Tired of doing db.session.add and db.session.commit to save your records? Have no fear, save is here. Note: This is for use with Flask-SQLAlchemy
from .user import User
def init_db(db):
"""Add a save() function to db.Model"""
def save(model):
db.session.add(model)
db.session.commit()
db.Model.save = save
db = SQLAlchemy()
init_db(db)
u = User(email='foo@foo.com', password='test!1234#')
u.save()
import bcrypt
from .core import db
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True, nullable=False)
password = db.Column(db.Text, nullable=False)
def __init__(self, email, password):
self.email = email
self.password = bcrypt.hashpw(password, bcrypt.gensalt(12))
def __repr__(self):
return '<User %s>' % self.email
@hartleybrody
Copy link

Awesome, simple idea! I just added it to my Flask Boilerplate project.

@Lemmah
Copy link

Lemmah commented May 10, 2018

Good stuff!! Thanks man!

@iMel408
Copy link

iMel408 commented Jun 15, 2019

Love this! Thank you!

Copy link

ghost commented Jun 24, 2019

What you did is also known as Active Record design.

You'd better move it to the model itself, passing as a mixin. This way you can add the mixin to whatever model you need.

db = SQLAlchemy()

class ActiveRecordMixin:
    def save(self):
        if self not in db.session:
            db.session.add(self)
        db.session.commit()

    def update(self, data: dict):
        for field, value in data.items():
            setattr(self, field, value)
        self.save()

    def delete(self):
        db.session.delete(self)
        db.session.commit()


class User(db.Model, ActiveRecordMixin):
    # your implementation

@erdumbledore
Copy link

@brunowerneck: Awesome! Thanks!

@imakecodes
Copy link

hi @brunowerneck, I did this here using with your and @dhrrgn suggestion :)

class BaseModel(db.Model):
    __abstract__ = True
    def save(self):
        if self not in db.session:
            db.session.add(self)
        db.session.commit()

    def update(self, data: dict):
        for field, value in data.items():
            setattr(self, field, value)
        self.save()

    def delete(self):
        db.session.delete(self)
        db.session.commit()


class User(BaseModel):
    # your implementation

@PurushothamanSrikanth
Copy link

@dhrrgn Good one!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment