add Base.as_dict() and Base.json()

Two utility functions for all of our ORM models that will
allow us to easily convert them to Python structures and
JSON data.

Signed-off-by: Kevin Morris <kevr@0cost.org>
This commit is contained in:
Kevin Morris 2021-06-13 10:48:31 -07:00
parent be3bab2ce0
commit bd8f528011
3 changed files with 57 additions and 0 deletions

View file

@ -1,10 +1,40 @@
import json
from sqlalchemy.ext.declarative import declarative_base
import aurweb.db
from aurweb import util
def to_dict(model):
return {
c.name: getattr(model, c.name)
for c in model.__table__.columns
}
def to_json(model, indent: int = None):
return json.dumps({
k: util.jsonify(v)
for k, v in to_dict(model).items()
}, indent=indent)
Base = declarative_base()
# Setup __table_args__ applicable to every table.
Base.__table_args__ = {
"autoload": True,
"autoload_with": aurweb.db.get_engine(),
"extend_existing": True
}
# Setup Base.as_dict and Base.json.
#
# With this, declarative models can use .as_dict() or .json()
# at any time to produce a dict and json out of table columns.
#
Base.as_dict = to_dict
Base.json = to_json