From d60faf3eabf887c0c905a7aca3bb71bc335d3122 Mon Sep 17 00:00:00 2001 From: Henning Jacobs Date: Mon, 22 Jul 2019 21:06:51 +0200 Subject: [PATCH] support asTable tabular representation (#34) * support asTable tabular representation * add repr --- pykube/query.py | 37 +++++++++++++++++++++++++++++++++++-- tests/test_query.py | 18 ++++++++++++++++++ 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/pykube/query.py b/pykube/query.py index 676ba1e..ac6dece 100644 --- a/pykube/query.py +++ b/pykube/query.py @@ -12,6 +12,28 @@ now = object() +class Table: + """ + Tabular resource representation + See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables + """ + def __init__(self, api_obj_class, obj: dict): + assert obj['kind'] == 'Table' + self.api_obj_class = api_obj_class + self.obj = obj + + def __repr__(self): + return "".format(kind=self.api_obj_class.kind, address=hex(id(self))) + + @property + def columns(self): + return self.obj['columnDefinitions'] + + @property + def rows(self): + return self.obj['rows'] + + class BaseQuery: def __init__(self, api, api_obj_class, namespace=None): @@ -21,6 +43,9 @@ def __init__(self, api, api_obj_class, namespace=None): self.selector = everything self.field_selector = everything + def __repr__(self): + return "".format(kind=self.api_obj_class.kind, address=hex(id(self))) + def all(self): return self._clone() @@ -112,8 +137,8 @@ def watch(self, since=None, *, params=None): query.resource_version = since return query - def execute(self): - kwargs = {"url": self._build_api_url()} + def execute(self, **kwargs): + kwargs["url"] = self._build_api_url() if self.api_obj_class.base: kwargs["base"] = self.api_obj_class.base if self.api_obj_class.version: @@ -124,6 +149,14 @@ def execute(self): r.raise_for_status() return r + def as_table(self) -> Table: + """ + Execute query and return result as Table (similar to what kubectl does) + See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables + """ + response = self.execute(headers={'Accept': 'application/json;as=Table;v=v1beta1;g=meta.k8s.io'}) + return Table(self.api_obj_class, response.json()) + def iterator(self): """ Execute the API request and return an iterator over the objects. This diff --git a/tests/test_query.py b/tests/test_query.py index 1390b74..4ca41d0 100644 --- a/tests/test_query.py +++ b/tests/test_query.py @@ -17,6 +17,11 @@ def test_get(api): Query(api, Pod).get(namespace='myns') +def test_repr(api): + query = Query(api, Pod) + assert repr(query).startswith('