0

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.

Ian Wilson
  • 6,223
  • 1
  • 16
  • 24

1 Answers1

0

A mixin let's you add methods and properties to a class outside of the direct class hierarchy. You can then use the same mixin to inject methods/properties into many classes, ie. preventing duplication by not writing that same to_dict() into each database model. This mixin helps extend model classes in this case but this pattern is a python pattern and not specific to SQLAlchemy.

This specific mixin just lets you convert a database model instance into a simple dictionary. It seems that the intent as you pointed out is to jsonify a database model instance. JSON does not support Dates so that is why special care is taken to convert datetimes into a str with isoformat().

record.to_dict() might output something like:

{
    "id": 100,
    "date": "2021-09-11"
    "country": "USA",
    "cases": 100000000,
    "deaths": 600000,
    "recoveries": 95000000
}

mixin explained on stackoverflow

multiple inheritance in python docs -- the mixin pattern utilizes multiple inheritance in Python

Ian Wilson
  • 6,223
  • 1
  • 16
  • 24