From 0ed6aa72e7d2fe397bdf1d536f6e55571a4797a4 Mon Sep 17 00:00:00 2001 From: zsdc Date: Fri, 28 Jul 2023 17:35:23 +0300 Subject: utils: T5410: Extended supported types in `convert_data()` Added `tuple`, `int`, `float`, `bool`, `None`, `bytearray`, `set`, `frozenset` types. --- python/vyos/utils/convert.py | 46 ++++++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 12 deletions(-) (limited to 'python/vyos/utils/convert.py') diff --git a/python/vyos/utils/convert.py b/python/vyos/utils/convert.py index ec2333ef0..9a8a1ff7d 100644 --- a/python/vyos/utils/convert.py +++ b/python/vyos/utils/convert.py @@ -144,32 +144,54 @@ def mac_to_eui64(mac, prefix=None): except: # pylint: disable=bare-except return -def convert_data(data): - """Convert multiple types of data to types usable in CLI + +def convert_data(data) -> dict | list | tuple | str | int | float | bool | None: + """Filter and convert multiple types of data to types usable in CLI/API + + WARNING: Must not be used for anything except formatting output for API or CLI + + On the output allowed everything supported in JSON. Args: - data (str | bytes | list | OrderedDict): input data + data (Any): input data Returns: - str | list | dict: converted data + dict | list | tuple | str | int | float | bool | None: converted data """ from base64 import b64encode - from collections import OrderedDict - if isinstance(data, str): + # return original data for types which do not require conversion + if isinstance(data, str | int | float | bool | None): return data - if isinstance(data, bytes): - try: - return data.decode() - except UnicodeDecodeError: - return b64encode(data).decode() + if isinstance(data, list): list_tmp = [] for item in data: list_tmp.append(convert_data(item)) return list_tmp - if isinstance(data, OrderedDict): + + if isinstance(data, tuple): + list_tmp = list(data) + tuple_tmp = tuple(convert_data(list_tmp)) + return tuple_tmp + + if isinstance(data, bytes | bytearray): + try: + return data.decode() + except UnicodeDecodeError: + return b64encode(data).decode() + + if isinstance(data, set | frozenset): + list_tmp = convert_data(list(data)) + return list_tmp + + if isinstance(data, dict): dict_tmp = {} for key, value in data.items(): dict_tmp[key] = convert_data(value) return dict_tmp + + # do not return anything for other types + # which cannot be converted to JSON + # for example: complex | range | memoryview + return -- cgit v1.2.3