Skip to content

Instantly share code, notes, and snippets.

@cesarferradas
Created May 29, 2020 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cesarferradas/a047ac0b4b2a8a902083a2b5eddfe70b to your computer and use it in GitHub Desktop.
Save cesarferradas/a047ac0b4b2a8a902083a2b5eddfe70b to your computer and use it in GitHub Desktop.
def to_schema_type(t):
'''
Convert SQL Alchemy data types to Open API compatible strings
'''
if t in [sqlt.TEXT, sqlt.VARCHAR, sqlt.CHAR, sqlt.Enum, sqlt.DateTime, sqlt.Date]:
return 'string'
if t in [sqlt.INT, sqlt.INTEGER, sqlt.BIGINT]:
return 'integer'
if t in [sqlt.BOOLEAN]:
return 'boolean'
if t in [sqlt.ARRAY]:
return 'array'
return 'object'
# in your base model:
@classmethod
def to_schema(cls, name):
'''Convert a Model to a Open API compliant dictionary'''
schema = {
f'{name}': {
'type': 'object',
'properties': {}
}
}
for column in get_columns(cls):
schema[f'{name}']['properties'].update({
column.name: {
'type': utils.to_schema_type(column.type.python_type),
'readOnly': not (
column.name in cls._editable_fields
and column.name in cls._public_fields
)
}
})
return schema
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment