expandable.py 1.9 KB

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