<s> """<STR_LIT>""" <EOL> import inspect <EOL> from . import fields , builders , errors <EOL> def to_struct ( model ) : <EOL> """<STR_LIT>""" <EOL> from . models import Base <EOL> if not isinstance ( model , Base ) : <EOL> return model <EOL> model . validate ( ) <EOL> resp = { } <EOL> for name , field in model : <EOL> value = field . __get__ ( model ) <EOL> if value is None : <EOL> continue <EOL> if isinstance ( value , list ) : <EOL> resp [ name ] = [ to_struct ( item ) for item in value ] <EOL> else : <EOL> resp [ name ] = to_struct ( value ) <EOL> return resp <EOL> def to_json_schema ( cls ) : <EOL> """<STR_LIT>""" <EOL> builder = build_json_schema ( cls ) <EOL> return builder . build ( ) <EOL> def build_json_schema ( value , parent_builder = None ) : <EOL> from . models import Base <EOL> cls = value if inspect . isclass ( value ) else value . __class__ <EOL> if issubclass ( cls , Base ) : <EOL> return build_json_schema_object ( cls , parent_builder ) <EOL> else : <EOL> return build_json_schema_primitive ( cls , parent_builder ) <EOL> def build_json_schema_object ( cls , parent_builder = None ) : <EOL> builder = builders . ObjectBuilder ( cls , parent_builder ) <EOL> if builder . count_type ( builder . type ) > <NUM_LIT:1> : <EOL> return builder <EOL> for name , field in cls . iterate_over_fields ( ) : <EOL> if isinstance ( field , fields . EmbeddedField ) : <EOL> builder . add_field ( name , field , _parse_embedded ( field , builder ) ) <EOL> elif isinstance ( field , fields . ListField ) : <EOL> builder . add_field ( name , field , _parse_list ( field , builder ) ) <EOL> else : <EOL> builder . add_field ( name , field , _specify_field_type ( field ) ) <EOL> return builder <EOL> def _parse_list ( field , parent_builder ) : <EOL> builder = builders . ListBuilder ( parent_builder ) <EOL> for type in field . items_types : <EOL> builder . add_type_schema ( build_json_schema ( type , builder ) ) <EOL> return builder <EOL> def _parse_embedded ( field , parent_builder ) : <EOL> builder = builders . EmbeddedBuilder ( parent_builder ) <EOL> for type in field . types : <EOL> builder . add_type_schema ( build_json_schema ( type , builder ) ) <EOL> return builder <EOL> def build_json_schema_primitive ( cls , parent_builder ) : <EOL> builder = builders . PrimitiveBuilder ( parent_builder ) <EOL> builder . set_type ( cls ) <EOL> return builder <EOL> def _specify_field_type ( field ) : <EOL> if isinstance ( field , fields . StringField ) : <EOL> return { '<STR_LIT:type>' : '<STR_LIT:string>' } <EOL> elif isinstance ( field , fields . IntField ) : <EOL> return { '<STR_LIT:type>' : '<STR_LIT>' } <EOL> elif isinstance ( field , fields . FloatField ) : <EOL> return { '<STR_LIT:type>' : '<STR_LIT:float>' } <EOL> elif isinstance ( field , fields . BoolField ) : <EOL> return { '<STR_LIT:type>' : '<STR_LIT>' } <EOL> raise errors . FieldNotSupported ( <EOL> '<STR_LIT>' . format ( <EOL> field = type ( field ) . __class__ . __name__ ) ) </s>
