turbo_broccoli.custom.uuid
UUIDs
1""" 2UUIDs 3 4See also: 5 https://docs.python.org/3/library/uuid.html 6""" 7 8from typing import Any 9from uuid import UUID 10 11from ..context import Context 12from ..exceptions import DeserializationError, TypeNotSupported 13 14 15def _json_to_uuid_v1(dct: dict, ctx: Context) -> Any: 16 return UUID(hex=dct["hex"]) 17 18 19def from_json(dct: dict, ctx: Context) -> Any: 20 try: 21 decoders = { 22 1: _json_to_uuid_v1, 23 } 24 return decoders[dct["__version__"]](dct, ctx) 25 except KeyError as exc: 26 raise DeserializationError() from exc 27 28 29def to_json(obj: Any, ctx: Context) -> dict: 30 """ 31 Serializes a 32 [`uuid.UUID`](https://docs.python.org/3/library/uuid.html#uuid.UUID) object 33 into JSON. The return dict has the following structure 34 35 ```py 36 { 37 "__type__": "uuid", 38 "__version__": 1, 39 "hex": <str> 40 } 41 ``` 42 43 where `<hex>` is the hexadecimal representation of the UUID. The reason for 44 using this representation instead of others (e.g. int or bytes) is that in 45 string form, this is the shortest. 46 """ 47 if not isinstance(obj, UUID): 48 raise TypeNotSupported() 49 return {"__type__": "uuid", "__version__": 1, "hex": obj.hex}
30def to_json(obj: Any, ctx: Context) -> dict: 31 """ 32 Serializes a 33 [`uuid.UUID`](https://docs.python.org/3/library/uuid.html#uuid.UUID) object 34 into JSON. The return dict has the following structure 35 36 ```py 37 { 38 "__type__": "uuid", 39 "__version__": 1, 40 "hex": <str> 41 } 42 ``` 43 44 where `<hex>` is the hexadecimal representation of the UUID. The reason for 45 using this representation instead of others (e.g. int or bytes) is that in 46 string form, this is the shortest. 47 """ 48 if not isinstance(obj, UUID): 49 raise TypeNotSupported() 50 return {"__type__": "uuid", "__version__": 1, "hex": obj.hex}
Serializes a
uuid.UUID
object
into JSON. The return dict has the following structure
{
"__type__": "uuid",
"__version__": 1,
"hex": <str>
}
where <hex>
is the hexadecimal representation of the UUID. The reason for
using this representation instead of others (e.g. int or bytes) is that in
string form, this is the shortest.