I am using Flask 1.1.2 and Flask-SQLAlchemy 2.4.4 to create a RESTFul service.
I want all of my model classes to be serializable and so have written a base class that my models derive from. In my Serializable class, the method as_dict() returns the string value of a column. However, I want to be modify the method to:
- Return integers and floats (not their string version)
- Boolean types to be returned in valid JSON (i.e. true, false)
This is my code so far:
class Serializable():
def as_dict(self):
return {c.name: str(getattr(self, c.name)) for c in self.__table__.columns}
class DataFrequency(db.Model, Serializable):
__tablename__ = 'data_frequency'
__table_args__ = (
db.CheckConstraint('period > 0'),
)
id = db.Column(db.Integer, primary_key=True, server_default=text("nextval('data_frequency_id_seq'::regclass)"))
period = db.Column(db.Integer, nullable=False)
name = db.Column(db.Text, nullable=False, unique=True)
How may I modify the as_dict() method to correctly handle Integer (and it's variants), Floats (and it's variants) and Boolean column types?