def _format_output(self, request, action, action_result): fields = request.params.get('fields', None) if action not in ('index', 'show') or fields is None: return action_result if action == 'show': action_result = utils.apply_template(fields, action_result) return action_result sp = utils.split_by_comma(fields) top_level = [] items = [] for string in sp: if 'items' in string: items.append(string) else: top_level.append(string) res = {} if len(items) > 0: res['items'] = [] for string in top_level: dct = utils.apply_template(string, action_result) for key, val in dct.items(): res[key] = val for string in items: if '(' in string: dct = utils.apply_template(string, action_result) for key, val in dct.items(): res[key] = val elif string.startswith('items/'): string = string[len('items/'):] for element in action_result['items']: dct = utils.apply_template(string, element) res['items'].append(dct) return res
def test_apply_template(self): fields1 = 'one,two,three(smth,else/one)' fields2 = 'one/smth,five/smth' wrongfields1 = 'zero,one/smth' wrongfields2 = 'fgdfds)9342' dct = {'one': {'smth': 1, 'else': 0}, 'two': 2, 'three': [{'smth': 3, 'another': 'string', 'else': {'one': 1}}], 'four': 4, 'five': {'smth': 5} } expected1 = {'one': {'smth': 1, 'else': 0}, 'two': 2, 'three': [{'smth': 3, 'else': {'one': 1}}] } expected2 = {'one': {'smth': 1}, 'five': {'smth': 5} } res1 = utils.apply_template(fields1, dct) res2 = utils.apply_template(fields2, dct) self.assertEqual(res1, expected1) self.assertEqual(res2, expected2) self.assertRaises(ValueError, utils.apply_template, wrongfields1, dct) self.assertRaises(ValueError, utils.apply_template, wrongfields2, dct)