-
Notifications
You must be signed in to change notification settings - Fork 0
/
attributes.py
46 lines (35 loc) · 1.33 KB
/
attributes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import uuid
import pynamodb.attributes
# UUID Attribute will use as Dynamo hash key
class UUIDAttribute(pynamodb.attributes.UnicodeAttribute):
def serialize(self, value):
return super().serialize(str(value))
def deserialize(self, value):
return uuid.UUID(super().deserialize(value))
# Add custom attribute to serialize and deserialize data
class ResultAttribute(pynamodb.attributes.MapAttribute):
@classmethod
def is_raw(cls):
# Set to use as AttributeContainer
# https://pynamodb.readthedocs.io/en/latest/api.html#pynamodb.attributes.MapAttribute
return True
@staticmethod
def _parse_value(values):
return {
f'semester {idx+1}': val for idx, val in enumerate(values)
}
def serialize(self, values):
# Convert python list to native pynamo
if isinstance(values, (list, tuple)):
values = self._parse_value(values)
return super().serialize(values)
def get_value(self, value):
try:
# Convert from
# {'L': [{'N': '3.75'}, {'N': '3.17'}]}
# to
# {'M': {'semester 1': {'N': '3.75'}, 'semester 2': {'N': '3.17'}}}
value = {'M': self._parse_value(value['L'])}
except (KeyError, TypeError):
pass
return super().get_value(value)