pboot 3.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pboot/json/__init__.py ADDED
@@ -0,0 +1,170 @@
1
+ from __future__ import annotations
2
+
3
+ import json as _json
4
+ import typing as t
5
+
6
+ from ..globals import current_app
7
+ from .provider import _default
8
+
9
+ if t.TYPE_CHECKING: # pragma: no cover
10
+ from ..wrappers import Response
11
+
12
+
13
+ def dumps(obj: t.Any, **kwargs: t.Any) -> str:
14
+ """Serialize data as JSON.
15
+
16
+ If :data:`~pboot.current_app` is available, it will use its
17
+ :meth:`app.json.dumps() <pboot.json.provider.JSONProvider.dumps>`
18
+ method, otherwise it will use :func:`json.dumps`.
19
+
20
+ :param obj: The data to serialize.
21
+ :param kwargs: Arguments passed to the ``dumps`` implementation.
22
+
23
+ .. versionchanged:: 2.3
24
+ The ``app`` parameter was removed.
25
+
26
+ .. versionchanged:: 2.2
27
+ Calls ``current_app.json.dumps``, allowing an app to override
28
+ the behavior.
29
+
30
+ .. versionchanged:: 2.0.2
31
+ :class:`decimal.Decimal` is supported by converting to a string.
32
+
33
+ .. versionchanged:: 2.0
34
+ ``encoding`` will be removed in Pboot 2.1.
35
+
36
+ .. versionchanged:: 1.0.3
37
+ ``app`` can be passed directly, rather than requiring an app
38
+ context for configuration.
39
+ """
40
+ if current_app:
41
+ return current_app.json.dumps(obj, **kwargs)
42
+
43
+ kwargs.setdefault("default", _default)
44
+ return _json.dumps(obj, **kwargs)
45
+
46
+
47
+ def dump(obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:
48
+ """Serialize data as JSON and write to a file.
49
+
50
+ If :data:`~pboot.current_app` is available, it will use its
51
+ :meth:`app.json.dump() <pboot.json.provider.JSONProvider.dump>`
52
+ method, otherwise it will use :func:`json.dump`.
53
+
54
+ :param obj: The data to serialize.
55
+ :param fp: A file opened for writing text. Should use the UTF-8
56
+ encoding to be valid JSON.
57
+ :param kwargs: Arguments passed to the ``dump`` implementation.
58
+
59
+ .. versionchanged:: 2.3
60
+ The ``app`` parameter was removed.
61
+
62
+ .. versionchanged:: 2.2
63
+ Calls ``current_app.json.dump``, allowing an app to override
64
+ the behavior.
65
+
66
+ .. versionchanged:: 2.0
67
+ Writing to a binary file, and the ``encoding`` argument, will be
68
+ removed in Pboot 2.1.
69
+ """
70
+ if current_app:
71
+ current_app.json.dump(obj, fp, **kwargs)
72
+ else:
73
+ kwargs.setdefault("default", _default)
74
+ _json.dump(obj, fp, **kwargs)
75
+
76
+
77
+ def loads(s: str | bytes, **kwargs: t.Any) -> t.Any:
78
+ """Deserialize data as JSON.
79
+
80
+ If :data:`~pboot.current_app` is available, it will use its
81
+ :meth:`app.json.loads() <pboot.json.provider.JSONProvider.loads>`
82
+ method, otherwise it will use :func:`json.loads`.
83
+
84
+ :param s: Text or UTF-8 bytes.
85
+ :param kwargs: Arguments passed to the ``loads`` implementation.
86
+
87
+ .. versionchanged:: 2.3
88
+ The ``app`` parameter was removed.
89
+
90
+ .. versionchanged:: 2.2
91
+ Calls ``current_app.json.loads``, allowing an app to override
92
+ the behavior.
93
+
94
+ .. versionchanged:: 2.0
95
+ ``encoding`` will be removed in Pboot 2.1. The data must be a
96
+ string or UTF-8 bytes.
97
+
98
+ .. versionchanged:: 1.0.3
99
+ ``app`` can be passed directly, rather than requiring an app
100
+ context for configuration.
101
+ """
102
+ if current_app:
103
+ return current_app.json.loads(s, **kwargs)
104
+
105
+ return _json.loads(s, **kwargs)
106
+
107
+
108
+ def load(fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:
109
+ """Deserialize data as JSON read from a file.
110
+
111
+ If :data:`~pboot.current_app` is available, it will use its
112
+ :meth:`app.json.load() <pboot.json.provider.JSONProvider.load>`
113
+ method, otherwise it will use :func:`json.load`.
114
+
115
+ :param fp: A file opened for reading text or UTF-8 bytes.
116
+ :param kwargs: Arguments passed to the ``load`` implementation.
117
+
118
+ .. versionchanged:: 2.3
119
+ The ``app`` parameter was removed.
120
+
121
+ .. versionchanged:: 2.2
122
+ Calls ``current_app.json.load``, allowing an app to override
123
+ the behavior.
124
+
125
+ .. versionchanged:: 2.2
126
+ The ``app`` parameter will be removed in Pboot 2.3.
127
+
128
+ .. versionchanged:: 2.0
129
+ ``encoding`` will be removed in Pboot 2.1. The file must be text
130
+ mode, or binary mode with UTF-8 bytes.
131
+ """
132
+ if current_app:
133
+ return current_app.json.load(fp, **kwargs)
134
+
135
+ return _json.load(fp, **kwargs)
136
+
137
+
138
+ def jsonify(*args: t.Any, **kwargs: t.Any) -> Response:
139
+ """Serialize the given arguments as JSON, and return a
140
+ :class:`~pboot.Response` object with the ``application/json``
141
+ mimetype. A dict or list returned from a view will be converted to a
142
+ JSON response automatically without needing to call this.
143
+
144
+ This requires an active app context, and calls
145
+ :meth:`app.json.response() <pboot.json.provider.JSONProvider.response>`.
146
+
147
+ In debug mode, the output is formatted with indentation to make it
148
+ easier to read. This may also be controlled by the provider.
149
+
150
+ Either positional or keyword arguments can be given, not both.
151
+ If no arguments are given, ``None`` is serialized.
152
+
153
+ :param args: A single value to serialize, or multiple values to
154
+ treat as a list to serialize.
155
+ :param kwargs: Treat as a dict to serialize.
156
+
157
+ .. versionchanged:: 2.2
158
+ Calls ``current_app.json.response``, allowing an app to override
159
+ the behavior.
160
+
161
+ .. versionchanged:: 2.0.2
162
+ :class:`decimal.Decimal` is supported by converting to a string.
163
+
164
+ .. versionchanged:: 0.11
165
+ Added support for serializing top-level arrays. This was a
166
+ security risk in ancient browsers. See :ref:`security-json`.
167
+
168
+ .. versionadded:: 0.2
169
+ """
170
+ return current_app.json.response(*args, **kwargs) # type: ignore[return-value]
pboot/json/provider.py ADDED
@@ -0,0 +1,215 @@
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import decimal
5
+ import json
6
+ import typing as t
7
+ import uuid
8
+ import weakref
9
+ from datetime import date
10
+
11
+ from werkzeug.http import http_date
12
+
13
+ if t.TYPE_CHECKING: # pragma: no cover
14
+ from werkzeug.sansio.response import Response
15
+
16
+ from ..sansio.app import App
17
+
18
+
19
+ class JSONProvider:
20
+ """A standard set of JSON operations for an application. Subclasses
21
+ of this can be used to customize JSON behavior or use different
22
+ JSON libraries.
23
+
24
+ To implement a provider for a specific library, subclass this base
25
+ class and implement at least :meth:`dumps` and :meth:`loads`. All
26
+ other methods have default implementations.
27
+
28
+ To use a different provider, either subclass ``Pboot`` and set
29
+ :attr:`~pboot.Pboot.json_provider_class` to a provider class, or set
30
+ :attr:`app.json <pboot.Pboot.json>` to an instance of the class.
31
+
32
+ :param app: An application instance. This will be stored as a
33
+ :class:`weakref.proxy` on the :attr:`_app` attribute.
34
+
35
+ .. versionadded:: 2.2
36
+ """
37
+
38
+ def __init__(self, app: App) -> None:
39
+ self._app: App = weakref.proxy(app)
40
+
41
+ def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:
42
+ """Serialize data as JSON.
43
+
44
+ :param obj: The data to serialize.
45
+ :param kwargs: May be passed to the underlying JSON library.
46
+ """
47
+ raise NotImplementedError
48
+
49
+ def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:
50
+ """Serialize data as JSON and write to a file.
51
+
52
+ :param obj: The data to serialize.
53
+ :param fp: A file opened for writing text. Should use the UTF-8
54
+ encoding to be valid JSON.
55
+ :param kwargs: May be passed to the underlying JSON library.
56
+ """
57
+ fp.write(self.dumps(obj, **kwargs))
58
+
59
+ def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:
60
+ """Deserialize data as JSON.
61
+
62
+ :param s: Text or UTF-8 bytes.
63
+ :param kwargs: May be passed to the underlying JSON library.
64
+ """
65
+ raise NotImplementedError
66
+
67
+ def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:
68
+ """Deserialize data as JSON read from a file.
69
+
70
+ :param fp: A file opened for reading text or UTF-8 bytes.
71
+ :param kwargs: May be passed to the underlying JSON library.
72
+ """
73
+ return self.loads(fp.read(), **kwargs)
74
+
75
+ def _prepare_response_obj(
76
+ self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]
77
+ ) -> t.Any:
78
+ if args and kwargs:
79
+ raise TypeError("app.json.response() takes either args or kwargs, not both")
80
+
81
+ if not args and not kwargs:
82
+ return None
83
+
84
+ if len(args) == 1:
85
+ return args[0]
86
+
87
+ return args or kwargs
88
+
89
+ def response(self, *args: t.Any, **kwargs: t.Any) -> Response:
90
+ """Serialize the given arguments as JSON, and return a
91
+ :class:`~pboot.Response` object with the ``application/json``
92
+ mimetype.
93
+
94
+ The :func:`~pboot.json.jsonify` function calls this method for
95
+ the current application.
96
+
97
+ Either positional or keyword arguments can be given, not both.
98
+ If no arguments are given, ``None`` is serialized.
99
+
100
+ :param args: A single value to serialize, or multiple values to
101
+ treat as a list to serialize.
102
+ :param kwargs: Treat as a dict to serialize.
103
+ """
104
+ obj = self._prepare_response_obj(args, kwargs)
105
+ return self._app.response_class(self.dumps(obj), mimetype="application/json")
106
+
107
+
108
+ def _default(o: t.Any) -> t.Any:
109
+ if isinstance(o, date):
110
+ return http_date(o)
111
+
112
+ if isinstance(o, (decimal.Decimal, uuid.UUID)):
113
+ return str(o)
114
+
115
+ if dataclasses and dataclasses.is_dataclass(o):
116
+ return dataclasses.asdict(o) # type: ignore[arg-type]
117
+
118
+ if hasattr(o, "__html__"):
119
+ return str(o.__html__())
120
+
121
+ raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")
122
+
123
+
124
+ class DefaultJSONProvider(JSONProvider):
125
+ """Provide JSON operations using Python's built-in :mod:`json`
126
+ library. Serializes the following additional data types:
127
+
128
+ - :class:`datetime.datetime` and :class:`datetime.date` are
129
+ serialized to :rfc:`822` strings. This is the same as the HTTP
130
+ date format.
131
+ - :class:`uuid.UUID` is serialized to a string.
132
+ - :class:`dataclasses.dataclass` is passed to
133
+ :func:`dataclasses.asdict`.
134
+ - :class:`~markupsafe.Markup` (or any object with a ``__html__``
135
+ method) will call the ``__html__`` method to get a string.
136
+ """
137
+
138
+ default: t.Callable[[t.Any], t.Any] = staticmethod(_default)
139
+ """Apply this function to any object that :meth:`json.dumps` does
140
+ not know how to serialize. It should return a valid JSON type or
141
+ raise a ``TypeError``.
142
+ """
143
+
144
+ ensure_ascii = True
145
+ """Replace non-ASCII characters with escape sequences. This may be
146
+ more compatible with some clients, but can be disabled for better
147
+ performance and size.
148
+ """
149
+
150
+ sort_keys = True
151
+ """Sort the keys in any serialized dicts. This may be useful for
152
+ some caching situations, but can be disabled for better performance.
153
+ When enabled, keys must all be strings, they are not converted
154
+ before sorting.
155
+ """
156
+
157
+ compact: bool | None = None
158
+ """If ``True``, or ``None`` out of debug mode, the :meth:`response`
159
+ output will not add indentation, newlines, or spaces. If ``False``,
160
+ or ``None`` in debug mode, it will use a non-compact representation.
161
+ """
162
+
163
+ mimetype = "application/json"
164
+ """The mimetype set in :meth:`response`."""
165
+
166
+ def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:
167
+ """Serialize data as JSON to a string.
168
+
169
+ Keyword arguments are passed to :func:`json.dumps`. Sets some
170
+ parameter defaults from the :attr:`default`,
171
+ :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.
172
+
173
+ :param obj: The data to serialize.
174
+ :param kwargs: Passed to :func:`json.dumps`.
175
+ """
176
+ kwargs.setdefault("default", self.default)
177
+ kwargs.setdefault("ensure_ascii", self.ensure_ascii)
178
+ kwargs.setdefault("sort_keys", self.sort_keys)
179
+ return json.dumps(obj, **kwargs)
180
+
181
+ def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:
182
+ """Deserialize data as JSON from a string or bytes.
183
+
184
+ :param s: Text or UTF-8 bytes.
185
+ :param kwargs: Passed to :func:`json.loads`.
186
+ """
187
+ return json.loads(s, **kwargs)
188
+
189
+ def response(self, *args: t.Any, **kwargs: t.Any) -> Response:
190
+ """Serialize the given arguments as JSON, and return a
191
+ :class:`~pboot.Response` object with it. The response mimetype
192
+ will be "application/json" and can be changed with
193
+ :attr:`mimetype`.
194
+
195
+ If :attr:`compact` is ``False`` or debug mode is enabled, the
196
+ output will be formatted to be easier to read.
197
+
198
+ Either positional or keyword arguments can be given, not both.
199
+ If no arguments are given, ``None`` is serialized.
200
+
201
+ :param args: A single value to serialize, or multiple values to
202
+ treat as a list to serialize.
203
+ :param kwargs: Treat as a dict to serialize.
204
+ """
205
+ obj = self._prepare_response_obj(args, kwargs)
206
+ dump_args: dict[str, t.Any] = {}
207
+
208
+ if (self.compact is None and self._app.debug) or self.compact is False:
209
+ dump_args.setdefault("indent", 2)
210
+ else:
211
+ dump_args.setdefault("separators", (",", ":"))
212
+
213
+ return self._app.response_class(
214
+ f"{self.dumps(obj, **dump_args)}\n", mimetype=self.mimetype
215
+ )
pboot/json/tag.py ADDED
@@ -0,0 +1,327 @@
1
+ """
2
+ Tagged JSON
3
+ ~~~~~~~~~~~
4
+
5
+ A compact representation for lossless serialization of non-standard JSON
6
+ types. :class:`~pboot.sessions.SecureCookieSessionInterface` uses this
7
+ to serialize the session data, but it may be useful in other places. It
8
+ can be extended to support other types.
9
+
10
+ .. autoclass:: TaggedJSONSerializer
11
+ :members:
12
+
13
+ .. autoclass:: JSONTag
14
+ :members:
15
+
16
+ Let's see an example that adds support for
17
+ :class:`~collections.OrderedDict`. Dicts don't have an order in JSON, so
18
+ to handle this we will dump the items as a list of ``[key, value]``
19
+ pairs. Subclass :class:`JSONTag` and give it the new key ``' od'`` to
20
+ identify the type. The session serializer processes dicts first, so
21
+ insert the new tag at the front of the order since ``OrderedDict`` must
22
+ be processed before ``dict``.
23
+
24
+ .. code-block:: python
25
+
26
+ from pboot.json.tag import JSONTag
27
+
28
+ class TagOrderedDict(JSONTag):
29
+ __slots__ = ('serializer',)
30
+ key = ' od'
31
+
32
+ def check(self, value):
33
+ return isinstance(value, OrderedDict)
34
+
35
+ def to_json(self, value):
36
+ return [[k, self.serializer.tag(v)] for k, v in iteritems(value)]
37
+
38
+ def to_python(self, value):
39
+ return OrderedDict(value)
40
+
41
+ app.session_interface.serializer.register(TagOrderedDict, index=0)
42
+ """
43
+
44
+ from __future__ import annotations
45
+
46
+ import typing as t
47
+ from base64 import b64decode
48
+ from base64 import b64encode
49
+ from datetime import datetime
50
+ from uuid import UUID
51
+
52
+ from markupsafe import Markup
53
+ from werkzeug.http import http_date
54
+ from werkzeug.http import parse_date
55
+
56
+ from ..json import dumps
57
+ from ..json import loads
58
+
59
+
60
+ class JSONTag:
61
+ """Base class for defining type tags for :class:`TaggedJSONSerializer`."""
62
+
63
+ __slots__ = ("serializer",)
64
+
65
+ #: The tag to mark the serialized object with. If empty, this tag is
66
+ #: only used as an intermediate step during tagging.
67
+ key: str = ""
68
+
69
+ def __init__(self, serializer: TaggedJSONSerializer) -> None:
70
+ """Create a tagger for the given serializer."""
71
+ self.serializer = serializer
72
+
73
+ def check(self, value: t.Any) -> bool:
74
+ """Check if the given value should be tagged by this tag."""
75
+ raise NotImplementedError
76
+
77
+ def to_json(self, value: t.Any) -> t.Any:
78
+ """Convert the Python object to an object that is a valid JSON type.
79
+ The tag will be added later."""
80
+ raise NotImplementedError
81
+
82
+ def to_python(self, value: t.Any) -> t.Any:
83
+ """Convert the JSON representation back to the correct type. The tag
84
+ will already be removed."""
85
+ raise NotImplementedError
86
+
87
+ def tag(self, value: t.Any) -> dict[str, t.Any]:
88
+ """Convert the value to a valid JSON type and add the tag structure
89
+ around it."""
90
+ return {self.key: self.to_json(value)}
91
+
92
+
93
+ class TagDict(JSONTag):
94
+ """Tag for 1-item dicts whose only key matches a registered tag.
95
+
96
+ Internally, the dict key is suffixed with `__`, and the suffix is removed
97
+ when deserializing.
98
+ """
99
+
100
+ __slots__ = ()
101
+ key = " di"
102
+
103
+ def check(self, value: t.Any) -> bool:
104
+ return (
105
+ isinstance(value, dict)
106
+ and len(value) == 1
107
+ and next(iter(value)) in self.serializer.tags
108
+ )
109
+
110
+ def to_json(self, value: t.Any) -> t.Any:
111
+ key = next(iter(value))
112
+ return {f"{key}__": self.serializer.tag(value[key])}
113
+
114
+ def to_python(self, value: t.Any) -> t.Any:
115
+ key = next(iter(value))
116
+ return {key[:-2]: value[key]}
117
+
118
+
119
+ class PassDict(JSONTag):
120
+ __slots__ = ()
121
+
122
+ def check(self, value: t.Any) -> bool:
123
+ return isinstance(value, dict)
124
+
125
+ def to_json(self, value: t.Any) -> t.Any:
126
+ # JSON objects may only have string keys, so don't bother tagging the
127
+ # key here.
128
+ return {k: self.serializer.tag(v) for k, v in value.items()}
129
+
130
+ tag = to_json
131
+
132
+
133
+ class TagTuple(JSONTag):
134
+ __slots__ = ()
135
+ key = " t"
136
+
137
+ def check(self, value: t.Any) -> bool:
138
+ return isinstance(value, tuple)
139
+
140
+ def to_json(self, value: t.Any) -> t.Any:
141
+ return [self.serializer.tag(item) for item in value]
142
+
143
+ def to_python(self, value: t.Any) -> t.Any:
144
+ return tuple(value)
145
+
146
+
147
+ class PassList(JSONTag):
148
+ __slots__ = ()
149
+
150
+ def check(self, value: t.Any) -> bool:
151
+ return isinstance(value, list)
152
+
153
+ def to_json(self, value: t.Any) -> t.Any:
154
+ return [self.serializer.tag(item) for item in value]
155
+
156
+ tag = to_json
157
+
158
+
159
+ class TagBytes(JSONTag):
160
+ __slots__ = ()
161
+ key = " b"
162
+
163
+ def check(self, value: t.Any) -> bool:
164
+ return isinstance(value, bytes)
165
+
166
+ def to_json(self, value: t.Any) -> t.Any:
167
+ return b64encode(value).decode("ascii")
168
+
169
+ def to_python(self, value: t.Any) -> t.Any:
170
+ return b64decode(value)
171
+
172
+
173
+ class TagMarkup(JSONTag):
174
+ """Serialize anything matching the :class:`~markupsafe.Markup` API by
175
+ having a ``__html__`` method to the result of that method. Always
176
+ deserializes to an instance of :class:`~markupsafe.Markup`."""
177
+
178
+ __slots__ = ()
179
+ key = " m"
180
+
181
+ def check(self, value: t.Any) -> bool:
182
+ return callable(getattr(value, "__html__", None))
183
+
184
+ def to_json(self, value: t.Any) -> t.Any:
185
+ return str(value.__html__())
186
+
187
+ def to_python(self, value: t.Any) -> t.Any:
188
+ return Markup(value)
189
+
190
+
191
+ class TagUUID(JSONTag):
192
+ __slots__ = ()
193
+ key = " u"
194
+
195
+ def check(self, value: t.Any) -> bool:
196
+ return isinstance(value, UUID)
197
+
198
+ def to_json(self, value: t.Any) -> t.Any:
199
+ return value.hex
200
+
201
+ def to_python(self, value: t.Any) -> t.Any:
202
+ return UUID(value)
203
+
204
+
205
+ class TagDateTime(JSONTag):
206
+ __slots__ = ()
207
+ key = " d"
208
+
209
+ def check(self, value: t.Any) -> bool:
210
+ return isinstance(value, datetime)
211
+
212
+ def to_json(self, value: t.Any) -> t.Any:
213
+ return http_date(value)
214
+
215
+ def to_python(self, value: t.Any) -> t.Any:
216
+ return parse_date(value)
217
+
218
+
219
+ class TaggedJSONSerializer:
220
+ """Serializer that uses a tag system to compactly represent objects that
221
+ are not JSON types. Passed as the intermediate serializer to
222
+ :class:`itsdangerous.Serializer`.
223
+
224
+ The following extra types are supported:
225
+
226
+ * :class:`dict`
227
+ * :class:`tuple`
228
+ * :class:`bytes`
229
+ * :class:`~markupsafe.Markup`
230
+ * :class:`~uuid.UUID`
231
+ * :class:`~datetime.datetime`
232
+ """
233
+
234
+ __slots__ = ("tags", "order")
235
+
236
+ #: Tag classes to bind when creating the serializer. Other tags can be
237
+ #: added later using :meth:`~register`.
238
+ default_tags = [
239
+ TagDict,
240
+ PassDict,
241
+ TagTuple,
242
+ PassList,
243
+ TagBytes,
244
+ TagMarkup,
245
+ TagUUID,
246
+ TagDateTime,
247
+ ]
248
+
249
+ def __init__(self) -> None:
250
+ self.tags: dict[str, JSONTag] = {}
251
+ self.order: list[JSONTag] = []
252
+
253
+ for cls in self.default_tags:
254
+ self.register(cls)
255
+
256
+ def register(
257
+ self,
258
+ tag_class: type[JSONTag],
259
+ force: bool = False,
260
+ index: int | None = None,
261
+ ) -> None:
262
+ """Register a new tag with this serializer.
263
+
264
+ :param tag_class: tag class to register. Will be instantiated with this
265
+ serializer instance.
266
+ :param force: overwrite an existing tag. If false (default), a
267
+ :exc:`KeyError` is raised.
268
+ :param index: index to insert the new tag in the tag order. Useful when
269
+ the new tag is a special case of an existing tag. If ``None``
270
+ (default), the tag is appended to the end of the order.
271
+
272
+ :raise KeyError: if the tag key is already registered and ``force`` is
273
+ not true.
274
+ """
275
+ tag = tag_class(self)
276
+ key = tag.key
277
+
278
+ if key:
279
+ if not force and key in self.tags:
280
+ raise KeyError(f"Tag '{key}' is already registered.")
281
+
282
+ self.tags[key] = tag
283
+
284
+ if index is None:
285
+ self.order.append(tag)
286
+ else:
287
+ self.order.insert(index, tag)
288
+
289
+ def tag(self, value: t.Any) -> t.Any:
290
+ """Convert a value to a tagged representation if necessary."""
291
+ for tag in self.order:
292
+ if tag.check(value):
293
+ return tag.tag(value)
294
+
295
+ return value
296
+
297
+ def untag(self, value: dict[str, t.Any]) -> t.Any:
298
+ """Convert a tagged representation back to the original type."""
299
+ if len(value) != 1:
300
+ return value
301
+
302
+ key = next(iter(value))
303
+
304
+ if key not in self.tags:
305
+ return value
306
+
307
+ return self.tags[key].to_python(value[key])
308
+
309
+ def _untag_scan(self, value: t.Any) -> t.Any:
310
+ if isinstance(value, dict):
311
+ # untag each item recursively
312
+ value = {k: self._untag_scan(v) for k, v in value.items()}
313
+ # untag the dict itself
314
+ value = self.untag(value)
315
+ elif isinstance(value, list):
316
+ # untag each item recursively
317
+ value = [self._untag_scan(item) for item in value]
318
+
319
+ return value
320
+
321
+ def dumps(self, value: t.Any) -> str:
322
+ """Tag the value and dump it to a compact JSON string."""
323
+ return dumps(self.tag(value), separators=(",", ":"))
324
+
325
+ def loads(self, value: str) -> t.Any:
326
+ """Load data from a JSON string and deserialized any tagged objects."""
327
+ return self._untag_scan(loads(value))