comparison planemo/lib/python3.7/site-packages/galaxy/util/dictifiable.py @ 1:56ad4e20f292 draft

"planemo upload commit 6eee67778febed82ddd413c3ca40b3183a3898f1"
author guerler
date Fri, 31 Jul 2020 00:32:28 -0400
parents
children
comparison
equal deleted inserted replaced
0:d30785e31577 1:56ad4e20f292
1 import datetime
2 import uuid
3
4
5 def dict_for(obj, **kwds):
6 # Create dict to represent item.
7 return dict(
8 model_class=obj.__class__.__name__,
9 **kwds
10 )
11
12
13 class Dictifiable(object):
14 """ Mixin that enables objects to be converted to dictionaries. This is useful
15 when for sharing objects across boundaries, such as the API, tool scripts,
16 and JavaScript code. """
17
18 def to_dict(self, view='collection', value_mapper=None):
19 """
20 Return item dictionary.
21 """
22
23 if not value_mapper:
24 value_mapper = {}
25
26 def get_value(key, item):
27 """
28 Recursive helper function to get item values.
29 """
30 # FIXME: why use exception here? Why not look for key in value_mapper
31 # first and then default to to_dict?
32 try:
33 return item.to_dict(view=view, value_mapper=value_mapper)
34 except Exception:
35 if key in value_mapper:
36 return value_mapper.get(key)(item)
37 if type(item) == datetime.datetime:
38 return item.isoformat()
39 elif type(item) == uuid.UUID:
40 return str(item)
41 # Leaving this for future reference, though we may want a more
42 # generic way to handle special type mappings going forward.
43 # If the item is of a class that needs to be 'stringified' before being put into a JSON data structure
44 # elif type(item) in []:
45 # return str(item)
46 return item
47
48 # Create dict to represent item.
49 rval = dict_for(self)
50
51 # Fill item dict with visible keys.
52 try:
53 visible_keys = self.__getattribute__('dict_' + view + '_visible_keys')
54 except AttributeError:
55 raise Exception('Unknown Dictifiable view: %s' % view)
56 for key in visible_keys:
57 try:
58 item = self.__getattribute__(key)
59 if isinstance(item, list):
60 rval[key] = []
61 for i in item:
62 rval[key].append(get_value(key, i))
63 else:
64 rval[key] = get_value(key, item)
65 except AttributeError:
66 rval[key] = None
67
68 return rval