Guest User

Untitled

a guest
May 22nd, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.61 KB | None | 0 0
  1. from lib.errors import TypeConvertInvalid
  2.  
  3. SIMPLE_VALUE_TYPES = [str, int, float]
  4. BOOLABLE_TYPES = SIMPLE_VALUE_TYPES[:]
  5. BOOLABLE_TYPES.append(bool)
  6.  
  7. def convert(value, convert_func, parse_path, convertable_types=SIMPLE_VALUE_TYPES):
  8. if type(value) in convertable_types:
  9. try:
  10. return convert_func(value)
  11. except ValueError:
  12. pass
  13.  
  14. error_message = '%s: %s could not be converted' % (type(value), parse_path)
  15. raise TypeConvertInvalid(error_message)
  16.  
  17. def convert_to_boolean(value, parse_path):
  18. if str(value).lower() == 'true':
  19. return True
  20. if str(value).lower() == 'false':
  21. return False
  22.  
  23. return convert(value=value,
  24. convert_func=bool,
  25. parse_path=parse_path,
  26. convertable_types=BOOLABLE_TYPES)
  27.  
  28. def handle_list_param(param, schema, parse_path):
  29. if type(param) is not list:
  30. raise TypeConvertInvalid('%s: %s is not an list' % (type(param), parse_path))
  31.  
  32. items_schema = schema.get('items')
  33. if items_schema:
  34. new_param = []
  35. for index, ele in enumerate(param):
  36. _parse_path = parse_path + '[%d]' % index
  37. new_param.append(paramsconvert(ele, items_schema, parse_path=_parse_path))
  38. return new_param
  39.  
  40. def handle_object_params(param, schema, parse_path):
  41. if type(param) is not dict:
  42. raise TypeConvertInvalid('%s: %s is not an dict' % (type(param), parse_path))
  43.  
  44. properties = schema.get('properties')
  45. if properties:
  46. new_param = {}
  47. for key in properties.keys():
  48. value = param.get(key)
  49. if value is not None:
  50. _parse_path = parse_path + '[%s]' % key
  51. new_param[key] = paramsconvert(value, properties[key], parse_path=_parse_path)
  52. return new_param
  53.  
  54. def paramsconvert(param, schema, parse_path='param'):
  55. param_type = schema['type']
  56. if param_type == 'object':
  57. result = handle_object_params(param=param, schema=schema, parse_path=parse_path)
  58. if result: return result
  59. elif param_type == 'string':
  60. return convert(value=param, convert_func=str, parse_path=parse_path)
  61. elif param_type == 'int':
  62. return convert(value=param, convert_func=int, parse_path=parse_path)
  63. elif param_type == 'number':
  64. return convert(value=param, convert_func=float, parse_path=parse_path)
  65. elif param_type == 'boolean':
  66. return convert_to_boolean(value=param, parse_path=parse_path)
  67. elif param_type == 'array':
  68. result = handle_list_param(param=param, schema=schema, parse_path=parse_path)
  69. if result: return result
  70.  
  71. return param
Add Comment
Please, Sign In to add comment