From 124f15e9fdb14ff1518c9f95ed595cb5ae416437 Mon Sep 17 00:00:00 2001 From: Zara Date: Wed, 13 Apr 2016 17:21:58 +0000 Subject: [PATCH] Get storyboard resources by properties other than ID Before, you had to fetch resources via ID. This patch lets you get resources via other properties, eg: get a list of stories with a specific named tag. I'm committing this but it's really co-authored with SotK, ie: he walked me through it. :) Change-Id: I28dbfc95badb9153187b7a4449d6d3df65635a20 --- storyboardclient/base.py | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/storyboardclient/base.py b/storyboardclient/base.py index 8e09ec9..767a9f5 100644 --- a/storyboardclient/base.py +++ b/storyboardclient/base.py @@ -71,7 +71,7 @@ class BaseHTTPClient(client.HTTPClient): class BaseManager(base.CrudManager): - def build_url(self, base_url=None, **kwargs): + def build_url(self, base_url=None, method=None, **kwargs): # Overriding to use "url_key" instead of the "collection_key". # "key_id" is replaced with just "id" when querying a specific object. url = base_url if base_url is not None else '' @@ -82,6 +82,16 @@ class BaseManager(base.CrudManager): if entity_id is not None: url += '/%s' % entity_id + elif method == 'get': + first = True + for key, value in kwargs.iteritems(): + if first: + url += '?' + first = False + else: + url += '&' + url += '%s=%s' % (key, value) + return url def get(self, id): @@ -96,6 +106,27 @@ class BaseManager(base.CrudManager): query_kwargs = {"id": id} return self._get(self.build_url(**query_kwargs), self.key) + def get_all(self, **kwargs): + """Get resources by properties other than ID.""" + kwargs = self._filter_kwargs(kwargs) + return self._get_all(self.build_url(method='get', **kwargs), self.key) + + def _get_all(self, url, response_key=None): + """Get collection of stuff. + + Put here because we can't modify base.py in the OpenStack + APIclient (probably) + + :param url: a partial URL, e.g., '/servers' + :param response_key: the key to be looked up in response dictionary, + e.g., 'server'. If response_key is None - all response body + will be used. + """ + + body = self.client.get(url).json() + data = body[response_key] if response_key is not None else body + return [self.resource_class(self, item, loaded=True) for item in data] + def create(self, **kwargs): """Create a resource. @@ -190,4 +221,4 @@ class BaseObject(base.Resource): continue val = getattr(self, attr) if inspect.isclass(val) and issubclass(val, BaseNestedManager): - yield attr, val \ No newline at end of file + yield attr, val