hydrators.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # fixme: rename this moduleto serialize
  2. def hydrate_string(dry_value):
  3. return str(dry_value) if dry_value else ''
  4. def dehydrate_string(wet_value):
  5. return wet_value
  6. def hydrate_bool(dry_value):
  7. return dry_value == 'True'
  8. def dehydrate_bool(wet_value):
  9. return 'True' if wet_value else 'False'
  10. def hydrate_int(dry_value):
  11. return int(dry_value)
  12. def dehydrate_int(wet_value):
  13. return str(wet_value)
  14. def hydrate_list(dry_value):
  15. return [x for x in dry_value.split(',') if x]
  16. def dehydrate_list(wet_value):
  17. return ','.join(wet_value)
  18. VALUE_HYDRATORS = {
  19. 'string': (hydrate_string, dehydrate_string),
  20. 'bool': (hydrate_bool, dehydrate_bool),
  21. 'int': (hydrate_int, dehydrate_int),
  22. 'list': (hydrate_list, dehydrate_list),
  23. }
  24. def hydrate_value(python_type, dry_value):
  25. try:
  26. value_hydrator = VALUE_HYDRATORS[python_type][0]
  27. except KeyError:
  28. raise ValueError("%s type is not hydrateable" % python_type)
  29. return value_hydrator(dry_value)
  30. def dehydrate_value(python_type, wet_value):
  31. try:
  32. value_dehydrator = VALUE_HYDRATORS[python_type][1]
  33. except KeyError:
  34. raise ValueError("%s type is not dehydrateable" % python_type)
  35. return value_dehydrator(wet_value)