From 08b70c3e74d02cfc1180f6c6992cd22fb28d18e8 Mon Sep 17 00:00:00 2001 From: Angus Salkeld Date: Fri, 9 May 2014 08:28:14 +1000 Subject: [PATCH] Add a FindMixin class to help with getting resources by name Note: this is largely a copy of apiclient.base.ManagerWithFind but without the inheritance and the find() method which does not clash with the Manager find() - now called findone() (tests are in the folowing commit) Change-Id: I332f542a1bf372e239f7f4e6a760e3bffebb641c --- solumclient/common/base.py | 45 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/solumclient/common/base.py b/solumclient/common/base.py index 326c9eb..16e8d4d 100644 --- a/solumclient/common/base.py +++ b/solumclient/common/base.py @@ -13,6 +13,7 @@ # under the License. from solumclient.openstack.common.apiclient import base +from solumclient.openstack.common.apiclient import exceptions from solumclient.openstack.common.py3kcompat import urlutils @@ -92,6 +93,50 @@ class BaseManager(ManagerMixin, base.BaseManager): pass +class FindMixin(): + """Just `findone()`/`findall()` methods. + + Note: this is largely a copy of apiclient.base.ManagerWithFind + but without the inheritance and the find() method which + does not clash with the Manager find() - now called findone(). + """ + + def findone(self, **kwargs): + """Find a single item with attributes matching ``**kwargs``. + + This isn't very efficient: it loads the entire list then filters on + the Python side. + """ + matches = self.findall(**kwargs) + num_matches = len(matches) + if num_matches == 0: + msg = "No %s matching %s." % (self.resource_class.__name__, kwargs) + raise exceptions.NotFound(msg) + elif num_matches > 1: + raise exceptions.NoUniqueMatch() + else: + return matches[0] + + def findall(self, **kwargs): + """Find all items with attributes matching ``**kwargs``. + + This isn't very efficient: it loads the entire list then filters on + the Python side. + """ + found = [] + searches = kwargs.items() + + for obj in self.list(): + try: + if all(getattr(obj, attr) == value + for (attr, value) in searches): + found.append(obj) + except AttributeError: + continue + + return found + + class CrudManager(ManagerMixin, base.CrudManager): def list(self, base_url=None, **kwargs): """List the collection.