1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
3
# Copyright 2012 United States Government as represented by the
4
# Administrator of the National Aeronautics and Space Administration.
7
# Copyright 2012 Nebula, Inc.
9
# Licensed under the Apache License, Version 2.0 (the "License"); you may
10
# not use this file except in compliance with the License. You may obtain
11
# a copy of the License at
13
# http://www.apache.org/licenses/LICENSE-2.0
15
# Unless required by applicable law or agreed to in writing, software
16
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
18
# License for the specific language governing permissions and limitations
23
from horizon import exceptions
26
__all__ = ('APIResourceWrapper', 'APIDictWrapper',
27
'get_service_from_catalog', 'url_for',)
30
LOG = logging.getLogger(__name__)
33
class APIResourceWrapper(object):
34
""" Simple wrapper for api objects
36
Define _attrs on the child class and pass in the
37
api object as the only argument to the constructor
41
def __init__(self, apiresource):
42
self._apiresource = apiresource
44
def __getattr__(self, attr):
45
if attr in self._attrs:
46
# __getattr__ won't find properties
47
return self._apiresource.__getattribute__(attr)
49
LOG.debug('Attempted to access unknown attribute "%s" on'
50
' APIResource object of type "%s" wrapping resource of'
51
' type "%s"' % (attr, self.__class__,
52
self._apiresource.__class__))
53
raise AttributeError(attr)
56
class APIDictWrapper(object):
57
""" Simple wrapper for api dictionaries
59
Some api calls return dictionaries. This class provides identical
60
behavior as APIResourceWrapper, except that it will also behave as a
61
dictionary, in addition to attribute accesses.
63
Attribute access is the preferred method of access, to be
64
consistent with api resource objects from novclient.
66
def __init__(self, apidict):
67
self._apidict = apidict
69
def __getattr__(self, attr):
71
return self._apidict[attr]
73
msg = 'Unknown attribute "%(attr)s" on APIResource object ' \
74
'of type "%(cls)s"' % {'attr': attr, 'cls': self.__class__}
76
raise AttributeError(msg)
78
def __getitem__(self, item):
80
return self.__getattr__(item)
81
except AttributeError, e:
82
# caller is expecting a KeyError
85
def get(self, item, default=None):
87
return self.__getattr__(item)
88
except AttributeError:
92
def get_service_from_catalog(catalog, service_type):
94
for service in catalog:
95
if service['type'] == service_type:
100
def url_for(request, service_type, admin=False, endpoint_type='internalURL'):
101
catalog = request.user.service_catalog
102
service = get_service_from_catalog(catalog, service_type)
106
return service['endpoints'][0]['adminURL']
108
return service['endpoints'][0][endpoint_type]
109
except (IndexError, KeyError):
110
raise exceptions.ServiceCatalogException(service_type)
112
raise exceptions.ServiceCatalogException(service_type)