Last active
March 2, 2022 04:16
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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='[email protected]', password='test!1234#') | |
u.save() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Good stuff!! Thanks man!
Love this! Thank you!
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
@brunowerneck: Awesome! Thanks!
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
@dhrrgn Good one!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome, simple idea! I just added it to my Flask Boilerplate project.