conversion.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from decimal import Decimal, InvalidOperation
  2. from django.utils.translation import gettext as _
  3. from dcim.choices import CableLengthUnitChoices
  4. from netbox.choices import WeightUnitChoices
  5. __all__ = (
  6. 'to_grams',
  7. 'to_meters',
  8. )
  9. def to_grams(weight, unit) -> int:
  10. """
  11. Convert the given weight to integer grams.
  12. """
  13. try:
  14. if weight < 0:
  15. raise ValueError(_("Weight must be a positive number"))
  16. except TypeError:
  17. raise TypeError(_("Invalid value '{weight}' for weight (must be a number)").format(weight=weight))
  18. if unit == WeightUnitChoices.UNIT_KILOGRAM:
  19. return int(weight * 1000)
  20. if unit == WeightUnitChoices.UNIT_GRAM:
  21. return int(weight)
  22. if unit == WeightUnitChoices.UNIT_POUND:
  23. return int(weight * Decimal(453.592))
  24. if unit == WeightUnitChoices.UNIT_OUNCE:
  25. return int(weight * Decimal(28.3495))
  26. raise ValueError(
  27. _("Unknown unit {unit}. Must be one of the following: {valid_units}").format(
  28. unit=unit,
  29. valid_units=', '.join(WeightUnitChoices.values())
  30. )
  31. )
  32. def to_meters(length, unit) -> Decimal:
  33. """
  34. Convert the given length to meters, returning a Decimal value.
  35. """
  36. try:
  37. length = Decimal(length)
  38. except InvalidOperation:
  39. raise TypeError(_("Invalid value '{length}' for length (must be a number)").format(length=length))
  40. if length < 0:
  41. raise ValueError(_("Length must be a positive number"))
  42. if unit == CableLengthUnitChoices.UNIT_KILOMETER:
  43. return round(Decimal(length * 1000), 4)
  44. if unit == CableLengthUnitChoices.UNIT_METER:
  45. return round(Decimal(length), 4)
  46. if unit == CableLengthUnitChoices.UNIT_CENTIMETER:
  47. return round(Decimal(length / 100), 4)
  48. if unit == CableLengthUnitChoices.UNIT_MILE:
  49. return round(length * Decimal(1609.344), 4)
  50. if unit == CableLengthUnitChoices.UNIT_FOOT:
  51. return round(length * Decimal(0.3048), 4)
  52. if unit == CableLengthUnitChoices.UNIT_INCH:
  53. return round(length * Decimal(0.0254), 4)
  54. raise ValueError(
  55. _("Unknown unit {unit}. Must be one of the following: {valid_units}").format(
  56. unit=unit,
  57. valid_units=', '.join(CableLengthUnitChoices.values())
  58. )
  59. )