comparison env/lib/python3.9/site-packages/galaxy/util/dictifiable.py @ 0:4f3585e2f14b draft default tip

"planemo upload commit 60cee0fc7c0cda8592644e1aad72851dec82c959"
author shellac
date Mon, 22 Mar 2021 18:12:50 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4f3585e2f14b
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:
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