|
| 1 | +import logging |
| 2 | +import os |
| 3 | +from importlib.machinery import FileFinder |
| 4 | +from pkgutil import ModuleInfo, get_importer |
| 5 | + |
| 6 | +from django.conf import settings |
| 7 | +from django.db import models |
| 8 | +from django.urls import reverse |
| 9 | +from django.utils.translation import gettext as _ |
| 10 | + |
| 11 | +from netbox.models.features import SyncedDataMixin |
| 12 | +from utilities.querysets import RestrictedQuerySet |
| 13 | + |
| 14 | +__all__ = ( |
| 15 | + 'ManagedFile', |
| 16 | +) |
| 17 | + |
| 18 | +logger = logging.getLogger('netbox.core.files') |
| 19 | + |
| 20 | +ROOT_PATH_CHOICES = ( |
| 21 | + ('scripts', 'Scripts Root'), |
| 22 | + ('reports', 'Reports Root'), |
| 23 | +) |
| 24 | + |
| 25 | + |
| 26 | +class ManagedFile(SyncedDataMixin, models.Model): |
| 27 | + """ |
| 28 | + Database representation for a file on disk. |
| 29 | + """ |
| 30 | + created = models.DateTimeField( |
| 31 | + auto_now_add=True |
| 32 | + ) |
| 33 | + last_updated = models.DateTimeField( |
| 34 | + editable=False, |
| 35 | + blank=True, |
| 36 | + null=True |
| 37 | + ) |
| 38 | + file_root = models.CharField( |
| 39 | + max_length=1000, |
| 40 | + choices=ROOT_PATH_CHOICES |
| 41 | + ) |
| 42 | + file_path = models.FilePathField( |
| 43 | + editable=False, |
| 44 | + help_text=_("File path relative to the designated root path") |
| 45 | + ) |
| 46 | + |
| 47 | + objects = RestrictedQuerySet.as_manager() |
| 48 | + |
| 49 | + class Meta: |
| 50 | + ordering = ('file_root', 'file_path') |
| 51 | + constraints = ( |
| 52 | + models.UniqueConstraint( |
| 53 | + fields=('file_root', 'file_path'), |
| 54 | + name='%(app_label)s_%(class)s_unique_root_path' |
| 55 | + ), |
| 56 | + ) |
| 57 | + indexes = [ |
| 58 | + models.Index(fields=('file_root', 'file_path'), name='core_managedfile_root_path'), |
| 59 | + ] |
| 60 | + |
| 61 | + def __str__(self): |
| 62 | + return f'{self.get_file_root_display()}: {self.file_path}' |
| 63 | + |
| 64 | + def get_absolute_url(self): |
| 65 | + return reverse('core:managedfile', args=[self.pk]) |
| 66 | + |
| 67 | + @property |
| 68 | + def full_path(self): |
| 69 | + return os.path.join(self._resolve_root_path(), self.file_path) |
| 70 | + |
| 71 | + def _resolve_root_path(self): |
| 72 | + return { |
| 73 | + 'scripts': settings.SCRIPTS_ROOT, |
| 74 | + 'reports': settings.REPORTS_ROOT, |
| 75 | + }[self.file_root] |
| 76 | + |
| 77 | + def get_module_info(self): |
| 78 | + return ModuleInfo( |
| 79 | + module_finder=get_importer(self.file_root), |
| 80 | + name=self.file_path.split('.py')[0], |
| 81 | + ispkg=False |
| 82 | + ) |
0 commit comments