I am very new to Python and SqlAlchemy. I stumbled upon this code while learning using SqlALchemy with Flask. Can you please help me to understand the class DictMixIn class - what are we doing here? Why are we using this?
class DictMixIn:
def to_dict(self):
return {
column.name: getattr(self, column.name)
if not isinstance(
getattr(self, column.name), (datetime.datetime, datetime.date)
)
else getattr(self, column.name).isoformat()
for column in self.__table__.columns
}
class Record(Base, DictMixIn):
__tablename__ = "Records"
id = Column(Integer, primary_key=True, index=True)
date = Column(Date)
country = Column(String, index=True)
cases = Column(Integer)
deaths = Column(Integer)
recoveries = Column(Integer)
At the end, the following snipped code was used - I believe they are using to_dict function above to print it. Am I right?
def show_records():
records = app.session.query(models.Record).all()
return jsonify([record.to_dict() for record in records])
The original code is here - https://github.com/edkrueger/sars-flask I would really appreciate your help.