Fix day filter
[cds-indico.git] / indico / util / serializer.py
blobfb571554a56d8c358b2f9b712691225722cbd1eb
1 # This file is part of Indico.
2 # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
4 # Indico is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License as
6 # published by the Free Software Foundation; either version 3 of the
7 # License, or (at your option) any later version.
9 # Indico is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 # General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with Indico; if not, see <http://www.gnu.org/licenses/>.
17 from enum import Enum
19 from indico.core.errors import IndicoError
20 from indico.core.logger import Logger
23 class Serializer(object):
24 __public__ = []
26 def to_serializable(self, attr='__public__', converters=None):
27 serializable = {}
28 if converters is None:
29 converters = {}
30 for k in getattr(self, attr):
31 try:
32 if isinstance(k, tuple):
33 k, name = k
34 else:
35 k, name = k, k
37 v = getattr(self, k)
38 if callable(v): # to make it generic, we can get rid of it by properties
39 v = v()
40 if isinstance(v, Serializer):
41 v = v.to_serializable()
42 elif isinstance(v, list):
43 v = [e.to_serializable() for e in v]
44 elif isinstance(v, dict):
45 v = dict((k, vv.to_serializable() if isinstance(vv, Serializer) else vv)
46 for k, vv in v.iteritems())
47 elif isinstance(v, Enum):
48 v = v.name
49 if type(v) in converters:
50 v = converters[type(v)](v)
51 serializable[name] = v
52 except Exception:
53 msg = 'Could not retrieve {}.{}.'.format(self.__class__.__name__, k)
54 Logger.get('Serializer{}'.format(self.__class__.__name__)).exception(msg)
55 raise IndicoError(msg)
56 return serializable