config.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. from django.core.cache import cache
  2. from django.db import models
  3. from django.urls import reverse
  4. from django.utils.translation import gettext
  5. from django.utils.translation import gettext_lazy as _
  6. from utilities.querysets import RestrictedQuerySet
  7. __all__ = (
  8. 'ConfigRevision',
  9. )
  10. class ConfigRevision(models.Model):
  11. """
  12. An atomic revision of NetBox's configuration.
  13. """
  14. active = models.BooleanField(
  15. default=False
  16. )
  17. created = models.DateTimeField(
  18. verbose_name=_('created'),
  19. auto_now_add=True
  20. )
  21. comment = models.CharField(
  22. verbose_name=_('comment'),
  23. max_length=200,
  24. blank=True
  25. )
  26. data = models.JSONField(
  27. blank=True,
  28. null=True,
  29. verbose_name=_('configuration data')
  30. )
  31. objects = RestrictedQuerySet.as_manager()
  32. class Meta:
  33. ordering = ['-created']
  34. indexes = (
  35. models.Index(fields=('-created',)), # Default ordering
  36. )
  37. verbose_name = _('config revision')
  38. verbose_name_plural = _('config revisions')
  39. constraints = [
  40. models.UniqueConstraint(
  41. fields=('active',),
  42. condition=models.Q(active=True),
  43. name='unique_active_config_revision',
  44. )
  45. ]
  46. def __str__(self):
  47. if not self.pk:
  48. return gettext('Default configuration')
  49. if self.is_active:
  50. return gettext('Current configuration')
  51. return gettext('Config revision #{id}').format(id=self.pk)
  52. def __getattr__(self, item):
  53. if self.data and item in self.data:
  54. return self.data[item]
  55. return super().__getattribute__(item)
  56. def get_absolute_url(self):
  57. if not self.pk:
  58. return reverse('core:config') # Default config view
  59. return reverse('core:configrevision', args=[self.pk])
  60. def activate(self, update_db=True):
  61. """
  62. Cache the configuration data.
  63. Parameters:
  64. update_db: Mark the ConfigRevision as active in the database (default: True)
  65. """
  66. cache.set('config', self.data, None)
  67. cache.set('config_version', self.pk, None)
  68. if update_db:
  69. # Set all instances of ConfigRevision to false and set this instance to true
  70. ConfigRevision.objects.all().update(active=False)
  71. ConfigRevision.objects.filter(pk=self.pk).update(active=True)
  72. activate.alters_data = True
  73. @property
  74. def is_active(self):
  75. return self.active