Created
August 20, 2020 16:06
-
-
Save kovalbogdan95/73561ffb625915bbe6fa0465cb7f6bc3 to your computer and use it in GitHub Desktop.
SQLAlchemy singleton model
This file contains hidden or 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 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