Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from lib.errors import TypeConvertInvalid
- SIMPLE_VALUE_TYPES = [str, int, float]
- BOOLABLE_TYPES = SIMPLE_VALUE_TYPES[:]
- BOOLABLE_TYPES.append(bool)
- def convert(value, convert_func, parse_path, convertable_types=SIMPLE_VALUE_TYPES):
- if type(value) in convertable_types:
- try:
- return convert_func(value)
- except ValueError:
- pass
- error_message = '%s: %s could not be converted' % (type(value), parse_path)
- raise TypeConvertInvalid(error_message)
- def convert_to_boolean(value, parse_path):
- if str(value).lower() == 'true':
- return True
- if str(value).lower() == 'false':
- return False
- return convert(value=value,
- convert_func=bool,
- parse_path=parse_path,
- convertable_types=BOOLABLE_TYPES)
- def handle_list_param(param, schema, parse_path):
- if type(param) is not list:
- raise TypeConvertInvalid('%s: %s is not an list' % (type(param), parse_path))
- items_schema = schema.get('items')
- if items_schema:
- new_param = []
- for index, ele in enumerate(param):
- _parse_path = parse_path + '[%d]' % index
- new_param.append(paramsconvert(ele, items_schema, parse_path=_parse_path))
- return new_param
- def handle_object_params(param, schema, parse_path):
- if type(param) is not dict:
- raise TypeConvertInvalid('%s: %s is not an dict' % (type(param), parse_path))
- properties = schema.get('properties')
- if properties:
- new_param = {}
- for key in properties.keys():
- value = param.get(key)
- if value is not None:
- _parse_path = parse_path + '[%s]' % key
- new_param[key] = paramsconvert(value, properties[key], parse_path=_parse_path)
- return new_param
- def paramsconvert(param, schema, parse_path='param'):
- param_type = schema['type']
- if param_type == 'object':
- result = handle_object_params(param=param, schema=schema, parse_path=parse_path)
- if result: return result
- elif param_type == 'string':
- return convert(value=param, convert_func=str, parse_path=parse_path)
- elif param_type == 'int':
- return convert(value=param, convert_func=int, parse_path=parse_path)
- elif param_type == 'number':
- return convert(value=param, convert_func=float, parse_path=parse_path)
- elif param_type == 'boolean':
- return convert_to_boolean(value=param, parse_path=parse_path)
- elif param_type == 'array':
- result = handle_list_param(param=param, schema=schema, parse_path=parse_path)
- if result: return result
- return param
Add Comment
Please, Sign In to add comment