expandable.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import re
  2. from django import forms
  3. from django.utils.translation import gettext_lazy as _
  4. from utilities.forms.constants import *
  5. from utilities.forms.utils import expand_alphanumeric_pattern, expand_ipaddress_pattern
  6. __all__ = (
  7. 'ExpandableIPAddressField',
  8. 'ExpandableNameField',
  9. )
  10. class ExpandableNameField(forms.CharField):
  11. """
  12. A field which allows for numeric range expansion
  13. Example: 'Gi0/[1-3]' => ['Gi0/1', 'Gi0/2', 'Gi0/3']
  14. """
  15. def __init__(self, *args, **kwargs):
  16. super().__init__(*args, **kwargs)
  17. if not self.help_text:
  18. self.help_text = _(
  19. "Alphanumeric ranges are supported for bulk creation. Mixed cases and types within a single range are "
  20. "not supported (example: <code>[ge,xe]-0/0/[0-9]</code>)."
  21. )
  22. def to_python(self, value):
  23. if not value:
  24. return ''
  25. if re.search(ALPHANUMERIC_EXPANSION_PATTERN, value):
  26. return list(expand_alphanumeric_pattern(value))
  27. return [value]
  28. class ExpandableIPAddressField(forms.CharField):
  29. """
  30. A field which allows for expansion of IP address ranges
  31. Example: '192.0.2.[1-254]/24' => ['192.0.2.1/24', '192.0.2.2/24', '192.0.2.3/24' ... '192.0.2.254/24']
  32. """
  33. def __init__(self, *args, **kwargs):
  34. super().__init__(*args, **kwargs)
  35. if not self.help_text:
  36. self.help_text = _('Specify a numeric range to create multiple IPs.<br />'
  37. 'Example: <code>192.0.2.[1,5,100-254]/24</code>')
  38. def to_python(self, value):
  39. # Hackish address family detection but it's all we have to work with
  40. if '.' in value and re.search(IP4_EXPANSION_PATTERN, value):
  41. return list(expand_ipaddress_pattern(value, 4))
  42. elif ':' in value and re.search(IP6_EXPANSION_PATTERN, value):
  43. return list(expand_ipaddress_pattern(value, 6))
  44. return [value]