diff --git a/kr8s/_api.py b/kr8s/_api.py index 8f0466b5..6b6ea4d3 100644 --- a/kr8s/_api.py +++ b/kr8s/_api.py @@ -12,6 +12,8 @@ import aiohttp import httpx +from asyncache import cached +from cachetools import TTLCache from cryptography import x509 from ._auth import KubeAuth @@ -443,6 +445,9 @@ async def api_resources(self) -> dict: """Get the Kubernetes API resources.""" return await self._api_resources() + # Cache for 10 minutes because kubectl does + # https://github.com/kubernetes/kubernetes/blob/0fb71846df9babb6012a7fce22e2533e9d795baa/staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go#L253 + @cached(TTLCache(1, 600)) async def _api_resources(self) -> dict: """Get the Kubernetes API resources.""" resources = [] diff --git a/kr8s/tests/test_api.py b/kr8s/tests/test_api.py index d1f9ca2f..3543ed64 100644 --- a/kr8s/tests/test_api.py +++ b/kr8s/tests/test_api.py @@ -236,15 +236,6 @@ def test_sync_api_returns_sync_objects(): assert pods[0]._asyncio is False -def test_api_client_reuse_between_event_loops(): - async def get_api(): - await kr8s.asyncio.get("pods", namespace=kr8s.ALL) - - asyncio.run(get_api()) - asyncio.set_event_loop(asyncio.new_event_loop()) - asyncio.run(get_api()) - - async def test_api_names(example_pod_spec, ns): pod = await Pod(example_pod_spec) await pod.create() @@ -269,3 +260,12 @@ async def test_whoami(): async def test_whoami_sync(): api = kr8s.api() assert kr8s.whoami() == api.whoami() + + +async def test_api_resources_cache(caplog): + caplog.set_level("INFO") + api = await kr8s.asyncio.api() + await api.api_resources() + assert caplog.text.count('/apis/ "HTTP/1.1 200 OK"') == 1 + await api.api_resources() + assert caplog.text.count('/apis/ "HTTP/1.1 200 OK"') == 1 diff --git a/kr8s/tests/test_io.py b/kr8s/tests/test_io.py index 299efc60..cee24a7e 100644 --- a/kr8s/tests/test_io.py +++ b/kr8s/tests/test_io.py @@ -14,6 +14,8 @@ async def main(): api = await kr8s.asyncio.api() version = await api.version() assert "major" in version + api_resources = await api.api_resources() + assert api_resources trio.run(main) diff --git a/pyproject.toml b/pyproject.toml index 74439f90..b61bc467 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,6 +10,7 @@ requires-python = ">=3.8" dynamic = ["version"] dependencies = [ "aiohttp>=3.8.4", + "asyncache>=0.3.1", "cryptography>=35", "pyyaml>=6.0", "python-jsonpath>=0.7.1",