| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870 |
- from collections.abc import Mapping
- from copy import deepcopy
- from datetime import date, datetime, time, timedelta
- from decimal import Decimal
- from importlib import import_module
- from types import SimpleNamespace
- from django.apps import apps
- from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
- from django.contrib.contenttypes.models import ContentType
- from django.core.exceptions import FieldDoesNotExist
- from django.db import models
- from django.db.models import prefetch_related_objects
- from django.utils.datastructures import MultiValueDict
- from jinja2.exceptions import TemplateRuntimeError
- from netaddr import IPAddress, IPNetwork
- from rest_framework.fields import SkipField
- from rest_framework.relations import PKOnlyObject
- from rest_framework.serializers import Serializer
- from netbox.api.exceptions import SerializerNotFound
- from netbox.api.fields import RelatedObjectsField
- from netbox.api.filters import OrderingFilter
- from netbox.api.gfk_fields import GFKSerializerField
- from netbox.models.features import model_is_public
- from netbox.registry import registry
- from utilities.api import (
- _get_base_queryset,
- _get_declared_prefetches,
- _get_nested_serializer,
- get_annotations_for_serializer,
- get_fields_for_serializer,
- get_prefetches_for_serializer,
- get_serializer_for_model,
- )
- from utilities.json import render_native_values
- __all__ = (
- 'NATIVE_VALUE_TYPES',
- 'TemplateObject',
- 'TemplateObjectList',
- 'get_query_function',
- 'get_template_context_data',
- 'get_template_object',
- 'get_template_objects',
- 'template_json_default',
- 'to_template_data',
- )
- # Native values which templates receive as they are (e.g. an IPAddress' address), matched by exact type
- NATIVE_VALUE_TYPES = (IPAddress, IPNetwork, date, datetime, time, timedelta)
- # Values which to_template_data() passes through unchanged, matched by exact type
- _PLAIN_VALUE_TYPES = (str, int, float, Decimal, bool, *NATIVE_VALUE_TYPES)
- # The number of objects a TemplateObjectList loads at a time
- TEMPLATE_OBJECTS_CHUNK_SIZE = 1000
- # The related objects represented by each model's serializer (see _get_relations()), keyed by model
- _relations = {}
- # Marks a field holding generic object references ({object_type, object_id, object}), e.g. cable terminations
- _GENERIC_OBJECTS = object()
- # Marks a field for which an object has no value (e.g. an object the rendering user may not view)
- _MISSING = object()
- def get_template_object(instance, state):
- """
- Return a TemplateObject representing the given instance. The caller is responsible for ensuring that the rendering
- user is permitted to view it.
- """
- _check_state(state)
- model = type(instance)
- if _get_serializer_class(model) is None:
- raise ValueError(f"{model._meta.label} has no REST API serializer.")
- batch = _Batch(model, [instance.pk], state, state.cache, instance=instance)
- state.cache[(model, instance.pk)] = batch
- return TemplateObject({'id': instance.pk}, model, state, batch=batch)
- def get_template_objects(queryset, state):
- """
- Return a lazy TemplateObjectList representing the objects in the given queryset which the rendering user is
- permitted to view. A sliced queryset is represented by the same slice of those objects.
- """
- _check_state(state)
- if _get_serializer_class(queryset.model) is None or not hasattr(queryset, 'restrict'):
- raise ValueError(f"{queryset.model._meta.label} does not support restricted rendering.")
- if queryset.query.is_sliced:
- # A sliced queryset (e.g. interfaces[:5]) can't be restricted, so take the same slice of the permitted objects
- start, stop = queryset.query.low_mark, queryset.query.high_mark
- queryset = queryset.all()
- queryset.query.clear_limits()
- return TemplateObjectList(queryset, state)[start:stop]
- return TemplateObjectList(queryset, state)
- def get_query_function(state):
- """
- Return the query() function for restricted rendering, which returns the objects of a model matching the given REST
- API filters, limited to those the rendering user is permitted to view.
- """
- _check_state(state)
- def query(model, /, ordering=None, limit=None, **filters):
- return _query(state, model, ordering, limit, filters)
- return query
- def get_template_context_data(value):
- """
- Return a copy of a restricted rendering context for display, with each TemplateObject replaced by its full
- representation and each TemplateObjectList by its description.
- """
- if isinstance(value, TemplateObject):
- return deepcopy(value._get_full_data())
- if isinstance(value, TemplateObjectList):
- return repr(value)
- if isinstance(value, dict):
- return {key: get_template_context_data(item) for key, item in value.items()}
- if isinstance(value, list):
- return [get_template_context_data(item) for item in value]
- return value
- def template_json_default(obj):
- """
- JSON encoder hook for restricted rendering: TemplateObjects serialize to their full representation.
- """
- if isinstance(obj, TemplateObject):
- return obj._get_full_data()
- if isinstance(obj, TemplateObjectList):
- return [item._get_full_data() for item in obj]
- if isinstance(obj, Decimal):
- return float(obj)
- if type(obj) is timedelta:
- # As REST framework's JSON encoder renders it
- return str(obj.total_seconds())
- if type(obj) in NATIVE_VALUE_TYPES:
- # Rendered as in REST API responses
- return render_native_values(obj)
- raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
- class TemplateObject(Mapping):
- """
- A read-only representation of a NetBox object for restricted template rendering. Behaves as a dict holding the
- object's REST API representation. Fields are loaded on demand, as are related objects not fully represented,
- limited to those the rendering user is permitted to view.
- """
- def __init__(self, data, model, state, batch=None, batches=None):
- # The fields known without loading the object (e.g. its brief representation as a related object)
- self._data = data
- self._model = model
- self._state = state
- self._batch = batch
- self._batches = batches
- self._wrapped = {}
- def __getitem__(self, key):
- if key in self._wrapped:
- return self._wrapped[key]
- if key in self._data:
- value = self._data[key]
- else:
- value = self._load(key)
- if isinstance(value, TemplateObjectList):
- self._wrapped[key] = value
- return value
- if key not in _get_relations(self._model) and isinstance(value, (dict, list)):
- # Return a copy, so that a template can't alter the retained representation
- return deepcopy(value)
- self._wrapped[key] = self._wrap(key, value)
- return self._wrapped[key]
- def __iter__(self):
- return iter(self._get_full_data())
- def __len__(self):
- return len(self._get_full_data())
- def __bool__(self):
- # Always represents an object, so avoid loading it (via __len__) just to test truthiness
- return True
- def __eq__(self, other):
- if isinstance(other, TemplateObject):
- return (self._model, self._data.get('id')) == (other._model, other._data.get('id'))
- return NotImplemented
- def __hash__(self):
- return hash((self._model, self._data.get('id')))
- def __str__(self):
- return str(self.get('display', ''))
- def __repr__(self):
- # Avoid loading the object (e.g. while formatting an error message)
- label = self._model._meta.label if self._model is not None else None
- return f'<TemplateObject {label} id={self._data.get("id")!r}>'
- def _get_batch(self):
- if self._batch is None and self._model is not None and (pk := self._data.get('id')) is not None:
- self._batch = _get_batch(self._model, pk, self._state, self._batches)
- return self._batch
- def _get_full_data(self):
- """
- Return the object's full representation, or the fields it was created with if the rendering user isn't
- permitted to view it.
- """
- if (batch := self._get_batch()) is not None and (data := batch.get_row(self._data['id'])) is not None:
- return data
- return self._data
- def _load(self, key):
- """
- Return a field the object wasn't created with (loaded for every object in its batch), or the list of objects
- related through an optional reverse relation (e.g. a device's interfaces).
- """
- if (batch := self._get_batch()) is None:
- raise KeyError(key)
- pk = self._data['id']
- if (value := batch.get(pk, key)) is _MISSING:
- if pk is None or (value := batch.get_related(pk, key)) is None:
- raise KeyError(key)
- return value
- def _wrap(self, key, value):
- relation = _get_relations(self._model).get(key)
- if relation is None or value is None:
- return deepcopy(value)
- if relation is _GENERIC_OBJECTS:
- if isinstance(value, list):
- return [self._wrap_generic_object(item) for item in value]
- return deepcopy(value)
- if isinstance(relation, str):
- # A generic foreign key: the related model is given by its content type field
- model = _get_model(self.get(relation))
- else:
- model = relation
- if model is not None and isinstance(value, list):
- return [self._wrap_object(item, model) for item in value]
- if model is not None and isinstance(value, dict):
- return self._wrap_object(value, model)
- return deepcopy(value)
- def _wrap_generic_object(self, item):
- if not isinstance(item, dict) or not isinstance(item.get('object'), dict):
- return deepcopy(item)
- if (model := _get_model(item.get('object_type'))) is None:
- return deepcopy(item)
- return {**deepcopy(item), 'object': self._wrap_object(item['object'], model)}
- def _wrap_object(self, data, model):
- # A related object is retained for as long as this one
- batches = self._batches if self._batch is None else self._batch.batches
- return TemplateObject(data, model, self._state, batches=batches)
- class TemplateObjectList:
- """
- A lazy, read-only list of TemplateObjects, limited to the objects the rendering user is permitted to view. Objects
- are loaded in chunks as the list is iterated, so a long list is never held in memory as a whole.
- """
- def __init__(self, queryset, state, limit=None, max_results=None, pks=None, batches=None):
- # Given the keys of its objects, the list never evaluates the queryset
- if pks is None:
- queryset = queryset.restrict(state.user, 'view')
- # Order an unordered queryset, so that the objects returned are deterministic
- queryset = queryset if queryset.ordered else queryset.order_by('pk')
- self._queryset = queryset
- self._state = state
- self._limit = limit
- self._max_results = max_results
- self._pks = pks
- self._batches = batches
- # The loaded objects, retained only for a list which fits in one chunk
- self._items = None
- self._first = None
- def __iter__(self):
- if self._items is not None:
- return iter(self._items)
- return self._iter_objects()
- def __reversed__(self):
- if self._items is not None:
- return reversed(self._items)
- return self._iter_objects(reverse=True)
- def __len__(self):
- if self._items is not None:
- return len(self._items)
- if self._pks is not None:
- return len(self._pks)
- count = self._queryset.count()
- return min(count, self._limit) if self._limit is not None else count
- def __bool__(self):
- if self._items is not None:
- return bool(self._items)
- if self._pks is not None:
- return bool(self._pks)
- return self._queryset.exists()
- def __getitem__(self, index):
- if self._items is not None:
- if isinstance(index, slice):
- items = self._items[index]
- sliced = self._slice([item['id'] for item in items])
- sliced._items = items
- return sliced
- return self._items[index]
- if not isinstance(index, (int, slice)):
- raise TypeError(f'list indices must be integers or slices, not {type(index).__name__}')
- # Read only the keys an index or slice needs (e.g. interfaces[:5]), where it can be determined
- if isinstance(index, int):
- stop = index + 1 if index >= 0 else None
- elif index.step in (None, 1) and (index.start or 0) >= 0 and index.stop is not None and index.stop >= 0:
- stop = index.stop
- else:
- stop = None
- if self._max_results is not None and (stop is None or stop > self._max_results):
- self._check_max_results()
- pks = self._get_pks(stop)
- if isinstance(index, slice):
- return self._slice(pks[index])
- return self._load([pks[index]], cache=True)[0]
- def __repr__(self):
- return f'<TemplateObjectList {self._queryset.model._meta.label}>'
- def all(self):
- return self
- def count(self):
- if self._pks is not None:
- return len(self._pks)
- if self._items is not None and self._limit is None:
- return len(self._items)
- return self._queryset.count()
- def first(self):
- if self._items is not None:
- return self._items[0] if self._items else None
- if self._first is None:
- self._first = self._load(self._get_pks(1), cache=True)
- return self._first[0] if self._first else None
- def _iter_objects(self, reverse=False):
- self._check_max_results()
- pks = self._get_pks()
- if len(pks) <= TEMPLATE_OBJECTS_CHUNK_SIZE:
- self._items = self._load(pks, cache=True)
- yield from reversed(self._items) if reverse else self._items
- return
- # Load a longer list one chunk at a time, without retaining or caching its objects
- starts = range(0, len(pks), TEMPLATE_OBJECTS_CHUNK_SIZE)
- for start in reversed(starts) if reverse else starts:
- items = self._load(pks[start:start + TEMPLATE_OBJECTS_CHUNK_SIZE])
- yield from reversed(items) if reverse else items
- def _check_max_results(self):
- if self._max_results is None or self._limit is not None or self._pks is not None:
- return
- if self._queryset[:self._max_results + 1].count() > self._max_results:
- raise TemplateRuntimeError(
- f"query() matched more than {self._max_results} objects. Narrow the filters, or pass a limit."
- )
- def _get_pks(self, stop=None):
- """
- Return the primary keys of the objects in the list, in order, up to the given position.
- """
- if self._pks is not None:
- return self._pks[:stop]
- stops = [value for value in (stop, self._limit) if value is not None]
- queryset = self._queryset.values_list('pk', flat=True)
- if stops:
- queryset = queryset[:min(stops)]
- # Remove any duplicates (e.g. from a distinct queryset ordered by a related field)
- return list(dict.fromkeys(queryset))
- def _load(self, pks, cache=False):
- return _load_objects(self._queryset.model, pks, self._state, cache=cache, batches=self._batches)
- def _slice(self, pks):
- return TemplateObjectList(self._queryset, self._state, pks=pks, batches=self._batches)
- class _Batch:
- """
- A group of objects of one model which are loaded together. Each field of their REST API representations is
- serialized for all of the objects at once, when a template first reads it from any of them.
- """
- def __init__(self, model, pks, state, batches, instance=None):
- self.model = model
- self.pks = pks
- self.state = state
- # Maps (model, pk) to the batch of each object retained for as long as these
- self.batches = batches
- # An object which the caller has ensured the user may view, used as is if the viewset's queryset omits it
- self.instance = instance
- self._instances = None
- self._columns = {}
- self._rows = None
- self._related = {}
- def get(self, pk, name):
- """
- Return the value of a field for the object with the given primary key, or _MISSING if it has none.
- """
- fields = _get_serializer(self.model, self.state)[1]
- if self._rows is None and fields is None:
- self._load_rows()
- if self._rows is not None:
- return self._rows[pk].get(name, _MISSING) if pk in self._rows else _MISSING
- if name not in fields:
- return _MISSING
- if name not in self._columns:
- self._load_column(name, fields[name])
- return self._columns[name].get(pk, _MISSING)
- def get_row(self, pk):
- """
- Return the full representation of the object with the given primary key, or None if the user may not view it.
- """
- if self._rows is None:
- self._load_rows()
- return self._rows.get(pk)
- def get_related(self, pk, name):
- """
- Return the list of objects related to an object through an optional reverse relation, or None if the name
- isn't one.
- """
- if name not in self._related:
- self._related[name] = self._load_related(name)
- if self._related[name] is None:
- return None
- queryset, pks, pending = self._related[name]
- if pk in pending:
- # Group the objects of this list with those of the lists which follow, so that they are loaded together
- parent_pks, count = [pk], len(pks[pk])
- for parent_pk in pending:
- if parent_pk != pk:
- if (count := count + len(pks[parent_pk])) > TEMPLATE_OBJECTS_CHUNK_SIZE:
- break
- parent_pks.append(parent_pk)
- for parent_pk in parent_pks:
- del pending[parent_pk]
- related = [related_pk for parent_pk in parent_pks for related_pk in pks[parent_pk]]
- _register(queryset.model, related, self.state, self.batches)
- return TemplateObjectList(queryset, self.state, pks=pks.get(pk, []), batches=self.batches)
- def get_instances(self):
- """
- Return the objects which the rendering user is permitted to view, by primary key.
- """
- if self._instances is None:
- queryset = self._get_queryset()
- if hasattr(queryset, 'annotate_config_context_data'):
- # Config context data is loaded only where it's rendered, as by the model's viewset
- queryset = queryset.defer('_config_context_data')
- self._instances = self._fetch(queryset)
- return self._instances
- def _get_queryset(self):
- # Start from the REST API viewset's queryset, which may annotate fields the serializer renders
- queryset = _get_base_queryset(self.model).filter(pk__in=self.pks)
- if self.instance is not None:
- return queryset
- return queryset.restrict(self.state.user, 'view') if hasattr(queryset, 'restrict') else queryset.none()
- def _fetch(self, queryset):
- instances = {instance.pk: instance for instance in queryset}
- if self.instance is not None and not instances:
- # Keyed as requested, since deleting an object clears its primary key
- instances[self.pks[0]] = self.instance
- return instances
- def _prepare(self, fields=None):
- """
- Return the objects by primary key, with the annotations and prefetches which the REST API uses to serialize
- the given fields (by default, all of them).
- """
- serializer_class = _get_serializer_class(self.model)
- names = set(get_fields_for_serializer(serializer_class, fields))
- base_queryset = _get_base_queryset(self.model)
- annotations = get_annotations_for_serializer(serializer_class, fields)
- if 'config_context' in names and hasattr(base_queryset, 'get_config_context_data_expression'):
- annotations['config_context_data'] = base_queryset.get_config_context_data_expression(
- only_invalidated=True
- )
- prefetches = [
- *_get_declared_prefetches(self.model, names),
- *get_prefetches_for_serializer(serializer_class, fields),
- ]
- # Skip any annotations the viewset's queryset already carries
- if annotations := {
- name: annotation for name, annotation in annotations.items()
- if name not in base_queryset.query.annotations
- }:
- # Annotated fields are serialized from objects of their own
- return self._fetch(self._get_queryset().annotate(**annotations).prefetch_related(*prefetches))
- instances = self.get_instances()
- if prefetches and instances:
- prefetch_related_objects(list(instances.values()), *prefetches)
- return instances
- def _load_column(self, name, field):
- column = {}
- instances = self._prepare((name,))
- _preload_custom_field_objects(field, instances.values())
- for pk, instance in instances.items():
- if (value := _serialize_field(field, instance)) is not _MISSING:
- column[pk] = to_template_data(value)
- self._columns[name] = column
- # Group the related objects which this field represents, so that they too are loaded together
- if (relation := _get_relations(self.model).get(name)) is not None:
- found = {}
- for pk, value in column.items():
- data = {name: value}
- if isinstance(relation, str):
- data[relation] = self.get(pk, relation)
- _find_related_objects(self.model, data, found)
- self._register_related(found)
- def _load_rows(self):
- serializer = _get_serializer(self.model, self.state)[0]
- instances = self._prepare()
- _preload_custom_field_objects(serializer.fields.get('custom_fields'), instances.values())
- self._rows = {
- pk: to_template_data(serializer.to_representation(instance))
- for pk, instance in instances.items()
- }
- found = {}
- for row in self._rows.values():
- _find_related_objects(self.model, row, found)
- self._register_related(found)
- def _register_related(self, found):
- for model, pks in found.items():
- _register(model, pks, self.state, self.batches)
- def _load_related(self, name):
- """
- Return the queryset of an optional reverse relation (e.g. a device's interfaces), the primary keys of the
- related objects the user may view for each object in the batch, and the objects whose lists are short enough
- to be retained but have yet to be read. Return None if the name isn't one.
- """
- serializer_class = _get_serializer_class(self.model)
- field = serializer_class._declared_fields.get(name)
- if name not in getattr(serializer_class.Meta, 'optional_fields', ()) or not isinstance(
- field, RelatedObjectsField
- ):
- return None
- queryset, parent = _get_related_objects(self.model, self.pks, field.relation)
- if _get_serializer_class(queryset.model) is None or not hasattr(queryset, 'restrict'):
- return None
- queryset = queryset.restrict(self.state.user, 'view')
- # Order an unordered queryset, so that the objects returned are deterministic
- queryset = queryset if queryset.ordered else queryset.order_by('pk')
- pks = {}
- for parent_pk, pk in queryset.values_list(parent, 'pk'):
- # A dict removes any duplicates (e.g. from a distinct queryset ordered by a related field)
- pks.setdefault(parent_pk, {})[pk] = None
- pks = {parent_pk: list(related) for parent_pk, related in pks.items()}
- pending = dict.fromkeys(
- parent_pk for parent_pk in self.pks
- if parent_pk in pks and len(pks[parent_pk]) <= TEMPLATE_OBJECTS_CHUNK_SIZE
- )
- return queryset, pks, pending
- #
- # Helpers
- #
- def _check_state(state):
- if state.user is None:
- raise ValueError("Restricted rendering of NetBox objects requires a user.")
- def _get_serializer_class(model):
- if model is None:
- return None
- try:
- return get_serializer_for_model(model)
- except SerializerNotFound:
- return None
- def _get_model(label):
- if not isinstance(label, str):
- return None
- try:
- return apps.get_model(label)
- except (LookupError, ValueError):
- return None
- def _query(state, label, ordering, limit, filters):
- model = _get_model(label.lower()) if isinstance(label, str) else None
- if model is None or not model_is_public(model):
- raise TemplateRuntimeError(f"query(): {label!r} is not a model which can be queried.")
- # FilterSets are registered when their module is imported, which may not have happened yet (e.g. in a worker)
- module_name = f'{model._meta.app_config.name}.filtersets'
- try:
- import_module(module_name)
- except ModuleNotFoundError as e:
- if e.name != module_name:
- raise
- filterset_class = registry['filtersets'].get(model._meta.label_lower)
- serializer_class = _get_serializer_class(model)
- queryset = _get_base_queryset(model).all()
- if filterset_class is None or serializer_class is None or not hasattr(queryset, 'restrict'):
- raise TemplateRuntimeError(f"query(): {label!r} is not a model which can be queried.")
- # Apply the filters
- data = MultiValueDict()
- no_results = False
- for name, value in filters.items():
- values = value if isinstance(value, (list, tuple)) else [value]
- # An empty list matches nothing (rather than being ignored, which would match everything)
- no_results = no_results or not values
- data.setlist(name, [_get_filter_value(name, item) for item in values])
- # Some filters (e.g. SavedFilter's "usable") depend on the requesting user
- filterset = filterset_class(data, queryset, request=SimpleNamespace(user=state.user))
- if unknown := [name for name in data if name not in filterset.filters]:
- raise TemplateRuntimeError(f"query(): unknown filters for {model._meta.label_lower}: {', '.join(unknown)}")
- if not filterset.is_valid():
- errors = '; '.join(f'{name}: {" ".join(messages)}' for name, messages in filterset.errors.items())
- raise TemplateRuntimeError(f"query(): invalid filters for {model._meta.label_lower}: {errors}")
- queryset = filterset.queryset.none() if no_results else filterset.qs
- # Apply the ordering, as the REST API does
- if ordering is not None:
- terms = ordering.split(',') if isinstance(ordering, str) else ordering
- terms = [str(term).strip() for term in terms]
- view = SimpleNamespace(serializer_class=serializer_class)
- ordering_filter = OrderingFilter()
- valid_terms = ordering_filter.remove_invalid_fields(queryset, terms, view, None)
- if invalid := [term for term in terms if term not in valid_terms]:
- raise TemplateRuntimeError(f"query(): invalid ordering for {model._meta.label_lower}: {', '.join(invalid)}")
- request = SimpleNamespace(query_params={ordering_filter.ordering_param: ','.join(terms)})
- queryset = ordering_filter.filter_queryset(request, queryset, view)
- max_results = state.max_results
- if limit is None:
- return TemplateObjectList(queryset, state, max_results=max_results)
- if type(limit) is not int or limit < 1 or (max_results is not None and limit > max_results):
- maximum = f' no greater than {max_results}' if max_results is not None else ''
- raise TemplateRuntimeError(f"query(): limit must be a positive integer{maximum}.")
- return TemplateObjectList(queryset, state, limit=limit)
- def _get_filter_value(name, value):
- """
- Return a filter value as it would appear in a REST API query string.
- """
- if value is None:
- return 'null'
- if isinstance(value, bool):
- return 'true' if value else 'false'
- if isinstance(value, str) and not value:
- raise TemplateRuntimeError(f"query(): the {name} filter was given an empty string.")
- if isinstance(value, (str, int, float, Decimal)):
- return str(value)
- if type(value) in NATIVE_VALUE_TYPES and type(value) is not timedelta:
- # Rendered as in REST API responses (e.g. a prefix as 192.0.2.0/24)
- return render_native_values(value)
- raise TemplateRuntimeError(
- f"query(): the {name} filter takes strings, numbers, IP addresses, dates and times (found "
- f"{type(value).__name__}). For a related object, pass its ID or slug."
- )
- def _get_related_objects(model, pks, relation):
- """
- Return a queryset of the objects related to any of the given objects through a reverse relation, a many-to-many
- field, or a GenericRelation, and the name of the field which holds the primary key of the object each relates to.
- """
- field = getattr(model, relation).field
- if isinstance(field, GenericRelation):
- return _get_base_queryset(field.related_model).filter(**{
- field.content_type_field_name: ContentType.objects.get_for_model(model),
- f'{field.object_id_field_name}__in': pks,
- }), field.object_id_field_name
- if field.model is model and field.many_to_many:
- # A many-to-many field declared on this model
- name = field.related_query_name()
- return _get_base_queryset(field.related_model).filter(**{f'{name}__in': pks}), name
- return _get_base_queryset(field.model).filter(**{f'{field.name}__in': pks}), field.attname
- def _get_relations(model):
- """
- Return the related models of the serializer fields which represent related objects, keyed by field name. A generic
- foreign key maps to the name of its content type field.
- """
- if model in _relations:
- return _relations[model]
- # Imported here to avoid a circular import (netbox.api.serializers imports extras.models)
- from netbox.api.serializers.generic import GenericObjectSerializer
- relations = {}
- if serializer_class := _get_serializer_class(model):
- for name, field in serializer_class._declared_fields.items():
- if isinstance(field, GFKSerializerField):
- try:
- model_field = model._meta.get_field(field.source or name)
- except FieldDoesNotExist:
- continue
- if isinstance(model_field, GenericForeignKey):
- relations[name] = model_field.ct_field
- elif isinstance(getattr(field, 'child', field), GenericObjectSerializer):
- relations[name] = _GENERIC_OBJECTS
- elif nested_serializer := _get_nested_serializer(field):
- relations[name] = type(nested_serializer).Meta.model
- _relations[model] = relations
- return relations
- def _find_related_objects(model, data, found):
- """
- Add the primary keys of the related objects represented within an object's (possibly partial) representation to
- found, by model.
- """
- for key, relation in _get_relations(model).items():
- if (value := data.get(key)) is None:
- continue
- values = value if isinstance(value, list) else [value]
- if relation is _GENERIC_OBJECTS:
- items = [
- (_get_model(item.get('object_type')), item.get('object')) for item in values if isinstance(item, dict)
- ]
- else:
- # A generic foreign key gives the related model by its content type field
- related_model = _get_model(data.get(relation)) if isinstance(relation, str) else relation
- items = [(related_model, item) for item in values]
- for related_model, item in items:
- if related_model is not None and isinstance(item, dict) and item.get('id') is not None:
- found.setdefault(related_model, {})[item['id']] = None
- _find_related_objects(related_model, item, found)
- def _find_batch(model, pk, state, batches):
- batch = batches.get((model, pk))
- if batch is None and batches is not state.cache:
- batch = state.cache.get((model, pk))
- return batch
- def _register(model, pks, state, batches):
- """
- Group any of the given objects not yet in a batch into batches, to be loaded together.
- """
- if _get_serializer_class(model) is None:
- return
- pks = [pk for pk in pks if _find_batch(model, pk, state, batches) is None]
- for start in range(0, len(pks), TEMPLATE_OBJECTS_CHUNK_SIZE):
- batch = _Batch(model, pks[start:start + TEMPLATE_OBJECTS_CHUNK_SIZE], state, batches)
- for pk in batch.pks:
- batches[(model, pk)] = batch
- def _get_batch(model, pk, state, batches=None):
- """
- Return the batch of the given object, or None if its model has no REST API serializer.
- """
- if batches is None:
- batches = state.cache
- if (batch := _find_batch(model, pk, state, batches)) is None:
- _register(model, [pk], state, batches)
- batch = batches.get((model, pk))
- return batch
- def _get_serializer(model, state):
- """
- Return the serializer used for the model's objects throughout a render, and its readable fields by name. The
- fields are None for a serializer which customizes its representation, which can only be rendered as a whole.
- """
- if model not in state.serializers:
- serializer = _get_serializer_class(model)(context={'request': None})
- fields = None
- if type(serializer).to_representation is Serializer.to_representation:
- fields = {name: field for name, field in serializer.fields.items() if not field.write_only}
- state.serializers[model] = (serializer, fields)
- return state.serializers[model]
- def _preload_custom_field_objects(field, instances):
- """
- Load the targets of the given objects' object and multi-object custom fields together, as the REST API does when
- serializing a list. The serializer is shared by every batch of its model, so the targets are added to its cache.
- """
- from extras.api.customfields import CustomFieldsDataField
- if isinstance(field, CustomFieldsDataField):
- field.parent.context.setdefault('cf_object_cache', {}).update(field.get_object_cache(instances))
- def _serialize_field(field, instance):
- """
- Return a serializer field's representation of an object, as Serializer.to_representation() derives it.
- """
- try:
- attribute = field.get_attribute(instance)
- except SkipField:
- return _MISSING
- if (attribute.pk if isinstance(attribute, PKOnlyObject) else attribute) is None:
- return None
- return field.to_representation(attribute)
- def _load_objects(model, pks, state, cache=False, batches=None):
- """
- Return TemplateObjects for the objects with the given primary keys which the rendering user is permitted to view,
- in the order of the keys. The objects are loaded together. If cache is True, they are retained in the given
- batches (by default, for the rest of the render); otherwise, only for as long as they are referenced.
- """
- if not pks or _get_serializer_class(model) is None:
- return []
- if not cache:
- batches = {}
- elif batches is None:
- batches = state.cache
- _register(model, pks, state, batches)
- objects = []
- for pk in pks:
- batch = _find_batch(model, pk, state, batches)
- if pk in batch.get_instances():
- objects.append(TemplateObject({'id': pk}, model, state, batch=batch))
- return objects
- def to_template_data(value, state=None):
- """
- Convert a value for restricted rendering to plain dicts, lists, strings, numbers, booleans, and None, keeping IP
- addresses, dates and times as they are. Given a render state, model instances are represented by TemplateObjects,
- and querysets and related managers by TemplateObjectLists.
- """
- if isinstance(value, (TemplateObject, TemplateObjectList)):
- return value
- if state is not None:
- if isinstance(value, models.Model):
- return get_template_object(value, state)
- if isinstance(value, models.Manager):
- # A related manager (e.g. device.interfaces) is represented by its objects
- value = value.all()
- if isinstance(value, models.QuerySet):
- return get_template_objects(value, state)
- if isinstance(value, dict):
- return {key: to_template_data(item, state) for key, item in value.items()}
- if isinstance(value, (list, tuple, set, frozenset)):
- return [to_template_data(item, state) for item in value]
- if value is None or type(value) in _PLAIN_VALUE_TYPES:
- return value
- if isinstance(value, str):
- # A str subclass (e.g. a SafeString) may return itself from str()
- return str.__str__(value)
- # Anything else (e.g. a lazy translation string) is represented by its string value
- return str(value)
|