diff --git a/example.py b/example.py index 76ff31a..48b2ebb 100644 --- a/example.py +++ b/example.py @@ -28,6 +28,7 @@ async def main(): await client.get_allmetrics() print(client.metrics) + await client.close() if __name__ == "__main__": asyncio.run(main()) \ No newline at end of file diff --git a/netdata/__init__.py b/netdata/__init__.py index 7c196f6..10d7243 100644 --- a/netdata/__init__.py +++ b/netdata/__init__.py @@ -21,7 +21,7 @@ class Netdata(object): """A class for handling connections with a Netdata instance.""" - def __init__(self, host, port=19999, tls=None, path=None, timeout=5.0): + def __init__(self, host, port=19999, tls=None, path=None, timeout=5.0, httpx_client:httpx.AsyncClient=None): """Initialize the connection to the Netdata instance.""" self.host = host self.port = port @@ -38,12 +38,22 @@ def __init__(self, host, port=19999, tls=None, path=None, timeout=5.0): self.base_url = URL.build( scheme=self.scheme, host=host, port=port, path=path ) + + if httpx_client is None: + self.client = httpx.AsyncClient() + else: + # This gives the possibility to use HomeAssistant implementation that has no blocking operation. + # See : https://developers.home-assistant.io/docs/asyncio_blocking_operations/#load_default_certs + self.client = httpx_client + + async def close(self): + """Close the client session.""" + await self.client.aclose() async def get_data(self, url) -> Dict: """Execute a request to a data endpoint.""" try: - async with httpx.AsyncClient() as client: - response = await client.get(str(url), timeout = self.timeout) + response = await self.client.get(str(url), timeout = self.timeout) except httpx.TimeoutException: raise except httpx.TransportError: diff --git a/pyproject.toml b/pyproject.toml index 542ba0f..fb3827c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "netdata" -version = "1.2.0" +version = "1.3.0" description = "Python API for interacting with Netdata" authors = ["Fabian Affolter "] license = "MIT"