1# Copyright 2013 Red Hat, Inc. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); you may 4# not use this file except in compliance with the License. You may obtain 5# a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12# License for the specific language governing permissions and limitations 13# under the License. 14 15import copy 16 17from oslo_reports.models import base as base_model 18from oslo_reports.views.json import generic as jsonviews 19from oslo_reports.views.text import generic as textviews 20from oslo_reports.views.xml import generic as xmlviews 21 22 23class ModelWithDefaultViews(base_model.ReportModel): 24 """A Model With Default Views of Various Types 25 26 A model with default views has several predefined views, 27 each associated with a given type. This is often used for 28 when a submodel should have an attached view, but the view 29 differs depending on the serialization format 30 31 Parameters are as the superclass, except for any 32 parameters ending in '_view': these parameters 33 get stored as default views. 34 35 The default 'default views' are 36 37 text 38 :class:`oslo_reports.views.text.generic.KeyValueView` 39 xml 40 :class:`oslo_reports.views.xml.generic.KeyValueView` 41 json 42 :class:`oslo_reports.views.json.generic.KeyValueView` 43 44 .. function:: to_type() 45 46 ('type' is one of the 'default views' defined for this model) 47 Serializes this model using the default view for 'type' 48 49 :rtype: str 50 :returns: this model serialized as 'type' 51 """ 52 53 def __init__(self, *args, **kwargs): 54 self.views = { 55 'text': textviews.KeyValueView(), 56 'json': jsonviews.KeyValueView(), 57 'xml': xmlviews.KeyValueView() 58 } 59 60 newargs = copy.copy(kwargs) 61 for k in kwargs: 62 if k.endswith('_view'): 63 self.views[k[:-5]] = kwargs[k] 64 del newargs[k] 65 super(ModelWithDefaultViews, self).__init__(*args, **newargs) 66 67 def set_current_view_type(self, tp, visited=None): 68 self.attached_view = self.views[tp] 69 super(ModelWithDefaultViews, self).set_current_view_type(tp, visited) 70 71 def __getattr__(self, attrname): 72 if attrname[:3] == 'to_': 73 if self.views[attrname[3:]] is not None: 74 return lambda: self.views[attrname[3:]](self) 75 else: 76 raise NotImplementedError(( 77 "Model {cn.__module__}.{cn.__name__} does not have" + 78 " a default view for " 79 "{tp}").format(cn=type(self), tp=attrname[3:])) 80 else: 81 return super(ModelWithDefaultViews, self).__getattr__(attrname) 82