Mercurial > libervia-backend
diff src/tools/common/data_format.py @ 2153:f67434fd88d2
tools (common/data_format): added dict2iterdict to yield dictionary from serialised complex values
author | Goffi <goffi@goffi.org> |
---|---|
date | Thu, 16 Feb 2017 00:40:50 +0100 |
parents | c8e561a5b2b6 |
children | 8b37a62336c3 |
line wrap: on
line diff
--- a/src/tools/common/data_format.py Mon Feb 13 20:59:09 2017 +0100 +++ b/src/tools/common/data_format.py Thu Feb 16 00:40:50 2017 +0100 @@ -18,10 +18,10 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. """ tools common to backend and frontends """ +# FIXME: json may be more appropriate than manual serialising like done here from sat.core import exceptions - def dict2iter(name, dict_, pop=False): """iterate into a list serialised in a dict @@ -54,6 +54,24 @@ else: idx += 1 +def dict2iterdict(name, dict_, extra_keys, pop=False): + """like dict2iter but yield dictionaries + + params are like in [dict2iter], extra_keys is used for extra dict keys. + e.g. dict2iterdict(comments, mb_data, ('node', 'service')) will yield dicts like: + {u'comments': u'value1', u'node': u'value2', u'service': u'value3'} + """ + # FIXME: this format seem overcomplicated, it may be more appropriate to use json here + if pop: + get=lambda d,k: d.pop(k) + else: + get=lambda d,k: d[k] + for idx, main_value in enumerate(dict2iter(name, dict_, pop=pop)): + ret = {name: main_value} + for k in extra_keys: + ret[k] = get(dict_, u'{}{}_{}'.format(name, (u'#' + unicode(idx)) if idx else u'', k)) + yield ret + def iter2dict(name, iter_, dict_=None, check_conflict=True): """Fill a dict with values from an iterable