Skip to content

Commit f4eb22f

Browse files
committed
add timeout parameter; allow passing a custom client session
1 parent 9722722 commit f4eb22f

1 file changed

Lines changed: 20 additions & 3 deletions

File tree

meteolux/async_api.py

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""A Python client for the MeteoLux API."""
2+
23
import typing
34
from typing import Any, Optional
45

@@ -23,14 +24,28 @@ class AsyncMeteoLuxClient:
2324
methods for all available endpoints, returning structured Pydantic models.
2425
"""
2526

26-
def __init__(self, base_url: str = 'https://metapi.ana.lu/api/v1') -> None:
27+
def __init__(
28+
self,
29+
base_url: str = 'https://metapi.ana.lu/api/v1',
30+
session: httpx.AsyncClient | None = None,
31+
timeout: int = 10,
32+
) -> None:
2733
"""Initializes the client with the base URL.
2834
2935
Args:
3036
base_url (str): The base URL for the API.
37+
session (httpx.AsyncClient, optional): An optional session to use.
38+
timeout (int, optional): The maximum number of seconds to wait before timing out a request.
3139
"""
40+
if base_url.endswith('/'):
41+
base_url = base_url[:-1]
42+
3243
self.base_url = base_url
33-
self.client = httpx.AsyncClient(base_url=self.base_url, timeout=10.0)
44+
45+
if session is None:
46+
self.client = httpx.AsyncClient(timeout=timeout)
47+
else:
48+
self.client = session
3449

3550
async def _request(self, method: str, endpoint: str, response_model: Optional[Any] = None, **kwargs: Any) -> Any:
3651
"""Internal method to handle all API requests and common error handling.
@@ -49,8 +64,10 @@ async def _request(self, method: str, endpoint: str, response_model: Optional[An
4964
httpx.HTTPStatusError: If the response status code is another error.
5065
httpx.RequestError: For network-related issues.
5166
"""
67+
_endpoint = f'{self.base_url}{endpoint}'
68+
5269
try:
53-
response = await self.client.request(method, endpoint, **kwargs)
70+
response = await self.client.request(method, _endpoint, **kwargs)
5471
response.raise_for_status()
5572

5673
if response.status_code == 204:

0 commit comments

Comments
 (0)