Debian Codegraph @

magnum_tempest_plugin/common/models.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 from oslo_serialization import jsonutils
14
15
16 class BaseModel(object):
17 """Superclass Responsible for converting json data to/from model"""
18
19 @classmethod
20 def from_json(cls, json_str):
21 return cls.from_dict(jsonutils.loads(json_str))
22
23 def to_json(self):
24 return jsonutils.dumps(self.to_dict())
25
26 @classmethod
27 def from_dict(cls, data):
28 model = cls()
29 for key in data:
30 setattr(model, key, data.get(key))
31 return model
32
33 def to_dict(self):
34 result = {}
35 for key in self.__dict__:
36 result[key] = getattr(self, key)
37 if isinstance(result[key], BaseModel):
38 result[key] = result[key].to_dict()
39 return result
40
41 def __str__(self):
42 return "%s" % self.to_dict()
43
44
45 class EntityModel(BaseModel):
46 """Superclass resposible from converting dict to instance of model"""
47
48 @classmethod
49 def from_dict(cls, data):
50 model = super(EntityModel, cls).from_dict(data)
51 if hasattr(model, cls.ENTITY_NAME):
52 val = getattr(model, cls.ENTITY_NAME)
53 setattr(model, cls.ENTITY_NAME, cls.MODEL_TYPE.from_dict(val))
54 return model
55
56
57 class CollectionModel(BaseModel):
58 """Superclass resposible from converting dict to list of models"""
59
60 @classmethod
61 def from_dict(cls, data):
62 model = super(CollectionModel, cls).from_dict(data)
63
64 collection = []
65 if hasattr(model, cls.COLLECTION_NAME):
66 for d in getattr(model, cls.COLLECTION_NAME):
67 collection.append(cls.MODEL_TYPE.from_dict(d))
68 setattr(model, cls.COLLECTION_NAME, collection)
69
70 return model