Re-org folders, onboard test folder, test config
[optf/osdf.git] / osdf / models / api / common.py
1 # -------------------------------------------------------------------------\r
2 #   Copyright (c) 2015-2017 AT&T Intellectual Property\r
3 #\r
4 #   Licensed under the Apache License, Version 2.0 (the "License");\r
5 #   you may not use this file except in compliance with the License.\r
6 #   You may obtain a copy of the License at\r
7 #\r
8 #       http://www.apache.org/licenses/LICENSE-2.0\r
9 #\r
10 #   Unless required by applicable law or agreed to in writing, software\r
11 #   distributed under the License is distributed on an "AS IS" BASIS,\r
12 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13 #   See the License for the specific language governing permissions and\r
14 #   limitations under the License.\r
15 #\r
16 # -------------------------------------------------------------------------\r
17 #\r
18 \r
19 import datetime\r
20 from pprint import pformat\r
21 \r
22 from dateutil.parser import parse\r
23 from schematics.exceptions import ConversionError\r
24 from schematics.models import Model\r
25 from schematics.types import DateTimeType\r
26 \r
27 \r
28 class OSDFModel(Model):\r
29     """Extends generic model with a couple of extra methods"""\r
30     def __str__(self):\r
31         """Return values of object's attributes -- excluding hidden or callable ones"""\r
32         def _str_format(x):\r
33             """Coerce as string for some special objects"""\r
34             return str(x) if isinstance(x, datetime.datetime) else x\r
35 \r
36         z1 = dict((x, getattr(self, x)) for x in dir(self)\r
37                   if not x.startswith("_") and not callable(getattr(self, x)))\r
38         z1 = dict((x, _str_format(y)) for x, y in z1.items())\r
39         return pformat(z1, depth=4, indent=2, width=1000)\r
40 \r
41     def __repr__(self):\r
42         """Return values of object's attributes -- excluding hidden or callable ones"""\r
43         return self.__str__()\r
44 \r
45 \r
46 class CustomISODateType(DateTimeType):\r
47     """Schematics doesn't support full ISO, so we use custom one"""\r
48     def to_native(self, value, context=None):\r
49         if isinstance(value, datetime.datetime):\r
50             return value\r
51         try:\r
52             return parse(value)\r
53         except:\r
54             raise ConversionError(u'Invalid timestamp {}'.format(value))\r