diff options
Diffstat (limited to 'ishtar_common/utils.py')
-rw-r--r-- | ishtar_common/utils.py | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/ishtar_common/utils.py b/ishtar_common/utils.py index e60fc0913..4f968af31 100644 --- a/ishtar_common/utils.py +++ b/ishtar_common/utils.py @@ -145,6 +145,77 @@ def check_model_access_control(request, model, available_perms=None): return allowed, own +def update_data(data_1, data_2): + """ + Update a data directory taking account of key detail + """ + res = {} + if not isinstance(data_1, dict) or not isinstance(data_2, dict): + return data_1 + for k in data_1: + if k not in data_2: + res[k] = data_1[k] + else: + res[k] = update_data(data_1[k], data_2[k]) + for k in data_2: + if k not in data_1: + res[k] = data_2[k] + return res + + +def move_dict_data(data, key1, key2): + """ + Move key1 value to key2 value in a data dict + :param data: data dict (with subdicts) + :param key1: key to move (with __ notation for hierarchy - begining with + "data__") + :param key2: target key (with __ notation for hierarchy - begining with + "data__") + :return: result data + """ + keys1 = key1.split('__') + keys2 = key2.split('__') + value = data + for idx, key in enumerate(keys1): + if not idx: + if key != 'data': + return data + continue + if key not in value: + return data + if idx == (len(keys1) - 1): # last + value = value.pop(key) # remove from data + else: + value = value[key] + + new_value = data + for idx, key in enumerate(keys2): + if not idx: + if key != 'data': + return data + continue + if idx == (len(keys2) - 1): # last + new_value[key] = value + else: + if key not in new_value: + new_value[key] = {} + new_value = new_value[key] + return data + + +def clean_empty_data(data): + """ + Clean empty branches of a data dict + """ + for key in data.keys(): + if data[key] in [{}, None, u""]: + data.pop(key) + continue + if isinstance(data[key], dict): + data[key] = clean_empty_data(data[key]) + return data + + class MultiValueDict(BaseMultiValueDict): def get(self, *args, **kwargs): v = super(MultiValueDict, self).getlist(*args, **kwargs) |