Search code examples
python-3.xsqlalchemyyaml

Generate Yaml file from SQLAlchemy class model


I have model defined like below in SQLAlchemy

class Users(db.Model, CRUD_MixIn):
    id = db.Column(db.Integer, primary_key=True)

    email = db.Column(db.String(250), nullable=False, unique=True)
    password = db.Column(db.String(250), nullable=False)
    name = db.Column(db.String(250), nullable=False)
    active = db.Column(db.Integer, nullable=False)
    creation_time = db.Column(db.TIMESTAMP,   server_default=db.func.current_timestamp(), nullable=False)
    role = db.Column(db.String(250), db.ForeignKey('roles.name'))

I want to generate a YAML file from it something like the following:

users:
 - email:email
 - password:string
 - name:string
 - active:boolean
 - creation_time:datetime
 - modification_time:datetime
 - role:string

is there any way to do it in python ?


Solution

  • You can iterate by columns and get python_types, something like this

    import yaml
    
    def yaml_from_model(model):
        columns = {c.name: c.type.python_type.__name__
                   for c in model.__table__.columns}
        return yaml.dump({model.__name__.lower(): columns},
                         default_flow_style=False)
    
    >> print yaml_from_model(Users)
    >> users:
         active: int
         creation_time: datetime
         email: str
         id: int
         name: str
         password: str
         role: str