Here is a serializer. My concern is to make the convert_to_internal
function more pythonic, efficient and ideally more functional. Maybe I could also get rid of three nested loops.
class TimeSerializer(serializers.Field):
DAYS = {
0: 'monday',
1: 'tuesday',
2: 'wednesday',
3: 'thursday',
4: 'friday',
5: 'saturday',
6: 'sunday',
7: 'holidays'
}
INVERSE_DAY = {v: k for k, v in DAYS.items()}
def __day_comparator(day_1, day_2):
"""
A helper to sort days, so they're sorted
as they appear in a week calendar.
"""
inverse_dict = TimeSerializer.INVERSE_DAY
return inverse_dict[day_1[0]] - inverse_dict[day_2[0]]
def convert_to_internal(self, agenda):
x = []
t = OrderedDict(sorted(agenda['timconf'].items(),
key=TimeSerializer.__day_comparator))
for day, items in t.items():
day_num = TimeSerializer.INVERSE_DAY[day]
for item in sorted(items, key=lambda k: k['begin']):
for attr in ['begin', 'end']:
if hasattr('item', attr):
item[attr] = item[attr] + day_num*24*60*60
x.append(TimeItem(**item))
p = ';'.join(map(str, x))
return "-t {} -n {} -p '{}'".format(agenda['timeZone'], agenda['locale'], p)