|
|
@@ -1,6 +1,6 @@
|
|
|
from collections.abc import Mapping
|
|
|
from copy import deepcopy
|
|
|
-from datetime import date, time
|
|
|
+from datetime import date, datetime, time, timedelta
|
|
|
from decimal import Decimal
|
|
|
from importlib import import_module
|
|
|
from types import SimpleNamespace
|
|
|
@@ -12,6 +12,7 @@ from django.core.exceptions import FieldDoesNotExist
|
|
|
from django.db import models
|
|
|
from django.utils.datastructures import MultiValueDict
|
|
|
from jinja2.exceptions import TemplateRuntimeError
|
|
|
+from netaddr import IPAddress, IPNetwork
|
|
|
|
|
|
from netbox.api.exceptions import SerializerNotFound
|
|
|
from netbox.api.fields import RelatedObjectsField
|
|
|
@@ -28,8 +29,10 @@ from utilities.api import (
|
|
|
get_prefetches_for_serializer,
|
|
|
get_serializer_for_model,
|
|
|
)
|
|
|
+from utilities.json import render_native_values
|
|
|
|
|
|
__all__ = (
|
|
|
+ 'NATIVE_VALUE_TYPES',
|
|
|
'TemplateObject',
|
|
|
'TemplateObjectList',
|
|
|
'get_query_function',
|
|
|
@@ -40,6 +43,12 @@ __all__ = (
|
|
|
'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
|
|
|
|
|
|
@@ -122,6 +131,12 @@ def template_json_default(obj):
|
|
|
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")
|
|
|
|
|
|
|
|
|
@@ -460,9 +475,12 @@ def _get_filter_value(name, 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 and numbers (found {type(value).__name__}). For a related object, "
|
|
|
- f"pass its ID or slug."
|
|
|
+ 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."
|
|
|
)
|
|
|
|
|
|
|
|
|
@@ -571,9 +589,9 @@ def _serialize(serializer_class, instance, many=False):
|
|
|
|
|
|
def to_template_data(value, state=None):
|
|
|
"""
|
|
|
- Convert a value for restricted rendering to plain dicts, lists, strings, numbers, booleans, and None. Given a
|
|
|
- render state, model instances are represented by TemplateObjects, and querysets and related managers by
|
|
|
- TemplateObjectLists.
|
|
|
+ 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
|
|
|
@@ -589,9 +607,7 @@ def to_template_data(value, state=None):
|
|
|
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 isinstance(value, (date, time)):
|
|
|
- return value.isoformat()
|
|
|
- if value is None or type(value) in (str, int, float, Decimal, bool):
|
|
|
+ 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()
|