config.py 2.4 KB

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