hydrators.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # fixme: rename this module to serialize
  2. def hydrate_string(dry_value):
  3. return str(dry_value) if dry_value else ""
  4. def dehydrate_string(wet_value):
  5. return str(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 or 0)
  12. def dehydrate_int(wet_value):
  13. return str(wet_value or 0)
  14. def hydrate_list(dry_value):
  15. if dry_value:
  16. return [x for x in dry_value.split(",") if x]
  17. return []
  18. def dehydrate_list(wet_value):
  19. return ",".join(wet_value) if wet_value else ""
  20. VALUE_HYDRATORS = {
  21. "string": (hydrate_string, dehydrate_string),
  22. "bool": (hydrate_bool, dehydrate_bool),
  23. "int": (hydrate_int, dehydrate_int),
  24. "list": (hydrate_list, dehydrate_list),
  25. }
  26. def hydrate_value(python_type, dry_value):
  27. try:
  28. value_hydrator = VALUE_HYDRATORS[python_type][0]
  29. except KeyError:
  30. raise ValueError("%s type is not hydrateable" % python_type)
  31. return value_hydrator(dry_value)
  32. def dehydrate_value(python_type, wet_value):
  33. try:
  34. value_dehydrator = VALUE_HYDRATORS[python_type][1]
  35. except KeyError:
  36. raise ValueError("%s type is not dehydrateable" % python_type)
  37. return value_dehydrator(wet_value)