Skip to content

Instantly share code, notes, and snippets.

@kovalbogdan95
Created August 20, 2020 16:06
Show Gist options
  • Save kovalbogdan95/73561ffb625915bbe6fa0465cb7f6bc3 to your computer and use it in GitHub Desktop.
Save kovalbogdan95/73561ffb625915bbe6fa0465cb7f6bc3 to your computer and use it in GitHub Desktop.
SQLAlchemy singleton model
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from rates.extensions import db
class LoadSingleton:
@classmethod
def load(cls):
id_ = {"id": 1}
try:
return db.session.query(cls).filter_by(**id_).one()
except NoResultFound:
try:
with db.session.begin_nested():
instance = cls(**id_)
db.session.add(instance)
db.session.commit()
return instance
except IntegrityError:
return db.session.query(cls).filter_by(**id_).one()
class Rate(db.Model, LoadSingleton):
"""
Model to store rate value
"""
__tablename__ = "rate"
id = db.Column(db.Integer, primary_key=True)
value = db.Column(db.Float, nullable=False, default=500)
def __repr__(self):
return f"<Rate value:{self.value}>"
# Usage
rate = Rate().load().value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment