lifeastroapi 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. lifeastroapi/__init__.py +68 -0
  2. lifeastroapi/_client.py +227 -0
  3. lifeastroapi/_core.py +28 -0
  4. lifeastroapi/_http.py +282 -0
  5. lifeastroapi/_params.py +89 -0
  6. lifeastroapi/_version.py +3 -0
  7. lifeastroapi/errors.py +152 -0
  8. lifeastroapi/py.typed +0 -0
  9. lifeastroapi/resources/__init__.py +188 -0
  10. lifeastroapi/resources/ashtakavarga.py +279 -0
  11. lifeastroapi/resources/calendar.py +281 -0
  12. lifeastroapi/resources/chart.py +1781 -0
  13. lifeastroapi/resources/dasha.py +1009 -0
  14. lifeastroapi/resources/eclipses.py +215 -0
  15. lifeastroapi/resources/festivals.py +245 -0
  16. lifeastroapi/resources/geo.py +177 -0
  17. lifeastroapi/resources/horoscope.py +155 -0
  18. lifeastroapi/resources/lalkitab.py +219 -0
  19. lifeastroapi/resources/meta.py +239 -0
  20. lifeastroapi/resources/milan.py +969 -0
  21. lifeastroapi/resources/muhurta.py +737 -0
  22. lifeastroapi/resources/narrative.py +2719 -0
  23. lifeastroapi/resources/numerology.py +417 -0
  24. lifeastroapi/resources/panchang.py +1709 -0
  25. lifeastroapi/resources/planet_moments.py +265 -0
  26. lifeastroapi/resources/prashna.py +335 -0
  27. lifeastroapi/resources/remedies.py +579 -0
  28. lifeastroapi/resources/reports.py +845 -0
  29. lifeastroapi/resources/tarot.py +207 -0
  30. lifeastroapi/resources/transit.py +615 -0
  31. lifeastroapi/resources/varshaphal.py +501 -0
  32. lifeastroapi/resources/western.py +5569 -0
  33. lifeastroapi/types.py +128 -0
  34. lifeastroapi-0.1.0.dist-info/METADATA +465 -0
  35. lifeastroapi-0.1.0.dist-info/RECORD +37 -0
  36. lifeastroapi-0.1.0.dist-info/WHEEL +4 -0
  37. lifeastroapi-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,68 @@
1
+ """Official Python SDK for LifeAstroAPI: Vedic astrology and the Hindu calendar.
2
+
3
+ from lifeastroapi import LifeAstro
4
+
5
+ client = LifeAstro(api_key="dv_live_...") # or set LIFEASTRO_API_KEY
6
+ day = client.panchang.basic(lat=23.0225, lon=72.5714, tz="Asia/Kolkata", lang="gu")
7
+
8
+ Docs: https://lifeastroapi.com/docs/
9
+ """
10
+
11
+ from ._client import API_KEY_ENV, DEFAULT_BASE_URL, AsyncLifeAstro, LifeAstro
12
+ from ._version import __version__
13
+ from .errors import (
14
+ AuthenticationError,
15
+ BadRequestError,
16
+ LifeAstroConnectionError,
17
+ LifeAstroError,
18
+ LifeAstroTimeoutError,
19
+ NotFoundError,
20
+ PaymentRequiredError,
21
+ PermissionDeniedError,
22
+ RateLimitError,
23
+ ServerError,
24
+ )
25
+ from .types import (
26
+ LOCALES,
27
+ Ayanamsa,
28
+ BirthInput,
29
+ HouseSystem,
30
+ Locale,
31
+ NatalWindowBirth,
32
+ QueryParams,
33
+ QueryValue,
34
+ RateLimit,
35
+ RequestOptions,
36
+ ResponseHook,
37
+ ResponseInfo,
38
+ )
39
+
40
+ __all__ = [
41
+ "API_KEY_ENV",
42
+ "DEFAULT_BASE_URL",
43
+ "LOCALES",
44
+ "AsyncLifeAstro",
45
+ "AuthenticationError",
46
+ "Ayanamsa",
47
+ "BadRequestError",
48
+ "BirthInput",
49
+ "HouseSystem",
50
+ "LifeAstro",
51
+ "LifeAstroConnectionError",
52
+ "LifeAstroError",
53
+ "LifeAstroTimeoutError",
54
+ "Locale",
55
+ "NatalWindowBirth",
56
+ "NotFoundError",
57
+ "PaymentRequiredError",
58
+ "PermissionDeniedError",
59
+ "QueryParams",
60
+ "QueryValue",
61
+ "RateLimit",
62
+ "RateLimitError",
63
+ "RequestOptions",
64
+ "ResponseHook",
65
+ "ResponseInfo",
66
+ "ServerError",
67
+ "__version__",
68
+ ]
@@ -0,0 +1,227 @@
1
+ """The LifeAstro clients: configuration, the request method every resource group
2
+ uses, and a generic escape hatch (``request`` / ``get``) for any endpoint.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ from collections.abc import Mapping
9
+ from types import TracebackType
10
+ from typing import Any
11
+
12
+ import httpx
13
+
14
+ from ._http import AsyncTransport, Config, SyncTransport
15
+ from ._version import __version__
16
+ from .errors import LifeAstroError
17
+ from .resources import AsyncResources, Resources
18
+ from .types import QueryValue, RequestOptions, ResponseHook
19
+
20
+ DEFAULT_BASE_URL = "https://api.lifeastroapi.com"
21
+ API_KEY_ENV = "LIFEASTRO_API_KEY"
22
+
23
+
24
+ def _resolve_config(
25
+ api_key: str | None,
26
+ base_url: str | None,
27
+ timeout: float,
28
+ max_retries: int,
29
+ default_headers: Mapping[str, str] | None,
30
+ on_response: ResponseHook | None,
31
+ ) -> Config:
32
+ key = api_key if api_key is not None else os.environ.get(API_KEY_ENV)
33
+ if not key:
34
+ raise LifeAstroError(
35
+ "LifeAstro: an API key is required. Pass api_key=... or set "
36
+ f"{API_KEY_ENV}. Get one at https://lifeastroapi.com/dashboard/keys",
37
+ code="missing_api_key",
38
+ status=0,
39
+ )
40
+ return Config(
41
+ api_key=key,
42
+ base_url=(base_url or DEFAULT_BASE_URL).rstrip("/"),
43
+ timeout=timeout,
44
+ max_retries=max(0, int(max_retries)),
45
+ user_agent=f"lifeastroapi-python/{__version__}",
46
+ default_headers=dict(default_headers or {}),
47
+ on_response=on_response,
48
+ )
49
+
50
+
51
+ class LifeAstro(Resources):
52
+ """The LifeAstroAPI client (blocking).
53
+
54
+ Args:
55
+ api_key: Your key (``dv_live_...``). Falls back to the
56
+ ``LIFEASTRO_API_KEY`` environment variable.
57
+ base_url: Override the API base URL, e.g. ``http://localhost:8080``.
58
+ timeout: Per-request timeout in seconds. Default 30.
59
+ max_retries: Automatic retries on 429, 5xx and network errors. Default 2.
60
+ default_headers: Extra headers sent on every request.
61
+ http_client: Your own ``httpx.Client`` (proxies, custom transport, tests).
62
+ The SDK does not close a client you pass in.
63
+ on_response: Called with the :class:`~lifeastroapi.ResponseInfo` of every call:
64
+ request id, credits left, rate limit, cache and language. Use it to log
65
+ usage or warn when credits run low. Exceptions raised inside it are ignored.
66
+
67
+ Example::
68
+
69
+ from lifeastroapi import LifeAstro
70
+
71
+ with LifeAstro(api_key="dv_live_...") as client:
72
+ day = client.panchang.basic(lat=19.076, lon=72.8777, tz="Asia/Kolkata")
73
+ chart = client.chart.planets(
74
+ date="1990-01-15", time="10:30", tz="Asia/Kolkata", lat=19.076, lon=72.8777
75
+ )
76
+ """
77
+
78
+ def __init__(
79
+ self,
80
+ api_key: str | None = None,
81
+ *,
82
+ base_url: str | None = None,
83
+ timeout: float = 30.0,
84
+ max_retries: int = 2,
85
+ default_headers: Mapping[str, str] | None = None,
86
+ http_client: httpx.Client | None = None,
87
+ on_response: ResponseHook | None = None,
88
+ ) -> None:
89
+ config = _resolve_config(
90
+ api_key, base_url, timeout, max_retries, default_headers, on_response
91
+ )
92
+ self._transport = SyncTransport(config, http_client)
93
+ super().__init__(self)
94
+
95
+ @property
96
+ def base_url(self) -> str:
97
+ """The API base URL this client calls."""
98
+ return self._transport.config.base_url
99
+
100
+ def request(
101
+ self,
102
+ path: str,
103
+ query: Mapping[str, QueryValue] | None = None,
104
+ *,
105
+ request_options: RequestOptions | None = None,
106
+ ) -> Any:
107
+ """Call any ``/v1/*`` endpoint directly and return the parsed JSON.
108
+
109
+ Useful for an endpoint this SDK version does not wrap yet. ``query``
110
+ uses the API's wire names; ``None`` and ``""`` values are left out::
111
+
112
+ client.request("/v1/panchang/tithi", {"lat": 28.61, "lon": 77.2, "tz": "Asia/Kolkata"})
113
+ """
114
+ return self._transport.request(path, query, request_options)
115
+
116
+ def get(
117
+ self,
118
+ path: str,
119
+ query: Mapping[str, QueryValue] | None = None,
120
+ *,
121
+ request_options: RequestOptions | None = None,
122
+ ) -> Any:
123
+ """Alias for :meth:`request`."""
124
+ return self.request(path, query, request_options=request_options)
125
+
126
+ def close(self) -> None:
127
+ """Close the underlying HTTP client (unless you passed your own)."""
128
+ self._transport.close()
129
+
130
+ def __enter__(self) -> LifeAstro:
131
+ return self
132
+
133
+ def __exit__(
134
+ self,
135
+ exc_type: type[BaseException] | None,
136
+ exc: BaseException | None,
137
+ tb: TracebackType | None,
138
+ ) -> None:
139
+ self.close()
140
+
141
+
142
+ class AsyncLifeAstro(AsyncResources):
143
+ """The LifeAstroAPI client for ``asyncio``. Same methods as :class:`LifeAstro`,
144
+ each one a coroutine.
145
+
146
+ Args:
147
+ api_key: Your key (``dv_live_...``). Falls back to the
148
+ ``LIFEASTRO_API_KEY`` environment variable.
149
+ base_url: Override the API base URL, e.g. ``http://localhost:8080``.
150
+ timeout: Per-request timeout in seconds. Default 30.
151
+ max_retries: Automatic retries on 429, 5xx and network errors. Default 2.
152
+ default_headers: Extra headers sent on every request.
153
+ http_client: Your own ``httpx.AsyncClient``. The SDK does not close a
154
+ client you pass in.
155
+ on_response: Called with the :class:`~lifeastroapi.ResponseInfo` of every call
156
+ (a plain function, not a coroutine). Exceptions raised inside it are ignored.
157
+
158
+ Example::
159
+
160
+ import asyncio
161
+ from lifeastroapi import AsyncLifeAstro
162
+
163
+ async def main() -> None:
164
+ async with AsyncLifeAstro() as client:
165
+ day = await client.panchang.basic(lat=23.0225, lon=72.5714, tz="Asia/Kolkata")
166
+
167
+ asyncio.run(main())
168
+ """
169
+
170
+ def __init__(
171
+ self,
172
+ api_key: str | None = None,
173
+ *,
174
+ base_url: str | None = None,
175
+ timeout: float = 30.0,
176
+ max_retries: int = 2,
177
+ default_headers: Mapping[str, str] | None = None,
178
+ http_client: httpx.AsyncClient | None = None,
179
+ on_response: ResponseHook | None = None,
180
+ ) -> None:
181
+ config = _resolve_config(
182
+ api_key, base_url, timeout, max_retries, default_headers, on_response
183
+ )
184
+ self._transport = AsyncTransport(config, http_client)
185
+ super().__init__(self)
186
+
187
+ @property
188
+ def base_url(self) -> str:
189
+ """The API base URL this client calls."""
190
+ return self._transport.config.base_url
191
+
192
+ async def request(
193
+ self,
194
+ path: str,
195
+ query: Mapping[str, QueryValue] | None = None,
196
+ *,
197
+ request_options: RequestOptions | None = None,
198
+ ) -> Any:
199
+ """Call any ``/v1/*`` endpoint directly and return the parsed JSON."""
200
+ return await self._transport.request(path, query, request_options)
201
+
202
+ async def get(
203
+ self,
204
+ path: str,
205
+ query: Mapping[str, QueryValue] | None = None,
206
+ *,
207
+ request_options: RequestOptions | None = None,
208
+ ) -> Any:
209
+ """Alias for :meth:`request`."""
210
+ return await self.request(path, query, request_options=request_options)
211
+
212
+ async def close(self) -> None:
213
+ """Close the underlying HTTP client (unless you passed your own)."""
214
+ await self._transport.close()
215
+
216
+ aclose = close
217
+
218
+ async def __aenter__(self) -> AsyncLifeAstro:
219
+ return self
220
+
221
+ async def __aexit__(
222
+ self,
223
+ exc_type: type[BaseException] | None,
224
+ exc: BaseException | None,
225
+ tb: TracebackType | None,
226
+ ) -> None:
227
+ await self.close()
lifeastroapi/_core.py ADDED
@@ -0,0 +1,28 @@
1
+ """The small surface a resource group needs from its client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any, Protocol
7
+
8
+ from .types import QueryValue, RequestOptions
9
+
10
+
11
+ class SyncCore(Protocol):
12
+ def request(
13
+ self,
14
+ path: str,
15
+ query: Mapping[str, QueryValue] | None = None,
16
+ *,
17
+ request_options: RequestOptions | None = None,
18
+ ) -> Any: ...
19
+
20
+
21
+ class AsyncCore(Protocol):
22
+ async def request(
23
+ self,
24
+ path: str,
25
+ query: Mapping[str, QueryValue] | None = None,
26
+ *,
27
+ request_options: RequestOptions | None = None,
28
+ ) -> Any: ...
lifeastroapi/_http.py ADDED
@@ -0,0 +1,282 @@
1
+ """HTTP transport: URL and query building, bearer auth, timeout, envelope
2
+ unwrapping, typed errors, bounded retries with exponential backoff that
3
+ honour ``Retry-After``, and the ``on_response`` hook. Same behaviour as the Node
4
+ SDK's ``src/http.ts``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import contextlib
11
+ import json
12
+ import math
13
+ import random
14
+ import time
15
+ from collections.abc import Mapping
16
+ from dataclasses import dataclass, field
17
+ from datetime import datetime, timezone
18
+ from email.utils import parsedate_to_datetime
19
+ from typing import Any
20
+ from urllib.parse import urlencode
21
+
22
+ import httpx
23
+
24
+ from ._params import _text
25
+ from .errors import (
26
+ LifeAstroConnectionError,
27
+ LifeAstroError,
28
+ LifeAstroTimeoutError,
29
+ error_from_response,
30
+ )
31
+ from .types import QueryValue, RateLimit, RequestOptions, ResponseHook, ResponseInfo
32
+
33
+ RETRYABLE_STATUS = frozenset({408, 425, 429, 500, 502, 503, 504})
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Config:
38
+ """Resolved client configuration."""
39
+
40
+ api_key: str = field(repr=False)
41
+ base_url: str
42
+ timeout: float
43
+ max_retries: int
44
+ user_agent: str
45
+ default_headers: Mapping[str, str]
46
+ on_response: ResponseHook | None = None
47
+
48
+
49
+ def encode_query(params: Mapping[str, QueryValue] | None) -> str:
50
+ """Encode params into a sorted query string, leaving out ``None`` and ``""``."""
51
+ if not params:
52
+ return ""
53
+ pairs = []
54
+ for key in sorted(params):
55
+ value = params[key]
56
+ if value is None or value == "":
57
+ continue
58
+ pairs.append((key, _text(value)))
59
+ return "?" + urlencode(pairs) if pairs else ""
60
+
61
+
62
+ def _normalize_path(path: str) -> str:
63
+ return path if path.startswith("/") else "/" + path
64
+
65
+
66
+ def build_url(config: Config, path: str, query: Mapping[str, QueryValue] | None) -> str:
67
+ return config.base_url + _normalize_path(path) + encode_query(query)
68
+
69
+
70
+ def build_headers(config: Config) -> dict[str, str]:
71
+ """Bearer token (header only, never in the URL), JSON accept, User-Agent.
72
+
73
+ ``default_headers`` are applied last, so a caller can override any of them.
74
+ """
75
+ headers = {
76
+ "Authorization": f"Bearer {config.api_key}",
77
+ "Accept": "application/json",
78
+ "User-Agent": config.user_agent,
79
+ }
80
+ headers.update(config.default_headers)
81
+ return headers
82
+
83
+
84
+ def parse_retry_after(value: str | None, now: datetime | None = None) -> float | None:
85
+ """Seconds from a ``Retry-After`` header: delta-seconds or an HTTP date."""
86
+ if not value:
87
+ return None
88
+ try:
89
+ seconds = float(value)
90
+ except ValueError:
91
+ pass
92
+ else:
93
+ return max(0.0, seconds) if math.isfinite(seconds) else None
94
+ try:
95
+ at = parsedate_to_datetime(value)
96
+ except (TypeError, ValueError, IndexError):
97
+ return None
98
+ if at is None:
99
+ return None
100
+ if at.tzinfo is None:
101
+ at = at.replace(tzinfo=timezone.utc)
102
+ current = now if now is not None else datetime.now(timezone.utc)
103
+ return max(0.0, (at - current).total_seconds())
104
+
105
+
106
+ def backoff_seconds(attempt: int, retry_after: float | None = None) -> float:
107
+ """Wait before retry ``attempt`` (0-based): ``Retry-After`` capped at 30 s,
108
+ else 0.5 s doubling up to 8 s, plus up to 0.25 s of jitter."""
109
+ if retry_after is not None:
110
+ return min(retry_after, 30.0)
111
+ return min(0.5 * 2.0**attempt, 8.0) + random.uniform(0, 0.25)
112
+
113
+
114
+ def _header_int(headers: httpx.Headers, name: str) -> int | None:
115
+ value = headers.get(name)
116
+ if value is None:
117
+ return None
118
+ try:
119
+ return int(value.strip())
120
+ except ValueError:
121
+ return None
122
+
123
+
124
+ def response_info(response: httpx.Response, path: str) -> ResponseInfo:
125
+ """Read the :class:`ResponseInfo` of a response. Header names are case-insensitive;
126
+ a header that is missing or not a number leaves its field ``None``."""
127
+ headers = response.headers
128
+ rate_limit: RateLimit | None = None
129
+ limit = _header_int(headers, "x-ratelimit-limit")
130
+ remaining = _header_int(headers, "x-ratelimit-remaining")
131
+ reset = _header_int(headers, "x-ratelimit-reset")
132
+ if limit is not None and remaining is not None and reset is not None:
133
+ with contextlib.suppress(OverflowError, OSError, ValueError):
134
+ rate_limit = RateLimit(
135
+ limit=limit,
136
+ remaining=remaining,
137
+ reset_at=datetime.fromtimestamp(reset, tz=timezone.utc),
138
+ )
139
+ return ResponseInfo(
140
+ status=response.status_code,
141
+ path=_normalize_path(path),
142
+ request_id=headers.get("x-request-id") or None,
143
+ credits_remaining=_header_int(headers, "x-credits-remaining"),
144
+ rate_limit=rate_limit,
145
+ cache=headers.get("x-cache") or None,
146
+ language=headers.get("content-language") or None,
147
+ )
148
+
149
+
150
+ def _emit(config: Config, opts: RequestOptions, response: httpx.Response, path: str) -> None:
151
+ """Call the client-level hook, then the per-call one. A hook that raises never
152
+ breaks the call."""
153
+ hooks = [hook for hook in (config.on_response, opts.get("on_response")) if hook is not None]
154
+ if not hooks:
155
+ return
156
+ info = response_info(response, path)
157
+ for hook in hooks:
158
+ with contextlib.suppress(Exception):
159
+ hook(info)
160
+
161
+
162
+ def _parse_body(content: bytes) -> Any:
163
+ if not content:
164
+ return None
165
+ try:
166
+ return json.loads(content)
167
+ except ValueError:
168
+ return content.decode("utf-8", errors="replace")
169
+
170
+
171
+ def _success(body: Any, raw: bool) -> Any:
172
+ # The API returns bare JSON today. A {data, meta} envelope is unwrapped if a
173
+ # response ever carries one, so adding it server-side is not a breaking change.
174
+ if not raw and isinstance(body, dict) and "data" in body:
175
+ return body["data"]
176
+ return body
177
+
178
+
179
+ def _transport_error(exc: httpx.RequestError, timeout: float) -> LifeAstroConnectionError:
180
+ err: LifeAstroConnectionError
181
+ if isinstance(exc, httpx.TimeoutException):
182
+ err = LifeAstroTimeoutError(f"Request timed out after {timeout:g}s")
183
+ else:
184
+ err = LifeAstroConnectionError(f"Network request failed: {exc}")
185
+ err.__cause__ = exc
186
+ return err
187
+
188
+
189
+ def _retryable(err: LifeAstroError) -> bool:
190
+ return err.status == 0 or err.status in RETRYABLE_STATUS
191
+
192
+
193
+ class SyncTransport:
194
+ """Blocking transport on ``httpx.Client``."""
195
+
196
+ def __init__(self, config: Config, http_client: httpx.Client | None) -> None:
197
+ self.config = config
198
+ self._owns_client = http_client is None
199
+ self._http = http_client if http_client is not None else httpx.Client()
200
+
201
+ def request(
202
+ self,
203
+ path: str,
204
+ query: Mapping[str, QueryValue] | None,
205
+ options: RequestOptions | None = None,
206
+ ) -> Any:
207
+ opts: RequestOptions = options or {}
208
+ url = build_url(self.config, path, query)
209
+ timeout = opts.get("timeout", self.config.timeout)
210
+ headers = build_headers(self.config)
211
+ attempt = 0
212
+ while True:
213
+ retry_after: float | None = None
214
+ answered: httpx.Response | None = None # an HTTP response, not a network failure
215
+ try:
216
+ response = self._http.request("GET", url, headers=headers, timeout=timeout)
217
+ except httpx.RequestError as exc:
218
+ err: LifeAstroError = _transport_error(exc, timeout)
219
+ else:
220
+ body = _parse_body(response.content)
221
+ if 200 <= response.status_code < 300:
222
+ _emit(self.config, opts, response, path)
223
+ return _success(body, opts.get("raw", False))
224
+ answered = response
225
+ retry_after = parse_retry_after(response.headers.get("retry-after"))
226
+ err = error_from_response(response.status_code, body, retry_after)
227
+ if attempt >= self.config.max_retries or not _retryable(err):
228
+ if answered is not None:
229
+ _emit(self.config, opts, answered, path)
230
+ raise err
231
+ time.sleep(backoff_seconds(attempt, retry_after))
232
+ attempt += 1
233
+
234
+ def close(self) -> None:
235
+ if self._owns_client:
236
+ self._http.close()
237
+
238
+
239
+ class AsyncTransport:
240
+ """Non-blocking transport on ``httpx.AsyncClient``."""
241
+
242
+ def __init__(self, config: Config, http_client: httpx.AsyncClient | None) -> None:
243
+ self.config = config
244
+ self._owns_client = http_client is None
245
+ self._http = http_client if http_client is not None else httpx.AsyncClient()
246
+
247
+ async def request(
248
+ self,
249
+ path: str,
250
+ query: Mapping[str, QueryValue] | None,
251
+ options: RequestOptions | None = None,
252
+ ) -> Any:
253
+ opts: RequestOptions = options or {}
254
+ url = build_url(self.config, path, query)
255
+ timeout = opts.get("timeout", self.config.timeout)
256
+ headers = build_headers(self.config)
257
+ attempt = 0
258
+ while True:
259
+ retry_after: float | None = None
260
+ answered: httpx.Response | None = None # an HTTP response, not a network failure
261
+ try:
262
+ response = await self._http.request("GET", url, headers=headers, timeout=timeout)
263
+ except httpx.RequestError as exc:
264
+ err: LifeAstroError = _transport_error(exc, timeout)
265
+ else:
266
+ body = _parse_body(response.content)
267
+ if 200 <= response.status_code < 300:
268
+ _emit(self.config, opts, response, path)
269
+ return _success(body, opts.get("raw", False))
270
+ answered = response
271
+ retry_after = parse_retry_after(response.headers.get("retry-after"))
272
+ err = error_from_response(response.status_code, body, retry_after)
273
+ if attempt >= self.config.max_retries or not _retryable(err):
274
+ if answered is not None:
275
+ _emit(self.config, opts, answered, path)
276
+ raise err
277
+ await asyncio.sleep(backoff_seconds(attempt, retry_after))
278
+ attempt += 1
279
+
280
+ async def close(self) -> None:
281
+ if self._owns_client:
282
+ await self._http.aclose()
@@ -0,0 +1,89 @@
1
+ """Helpers used by the generated resource methods to build the query.
2
+
3
+ The wire names they write (``birth.lat``, ``boy.date``, ``start_date``, ...)
4
+ are the contract with the API and match the Node SDK's ``src/params.ts``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from collections.abc import Mapping
11
+ from datetime import datetime, timedelta, timezone, tzinfo
12
+ from typing import Any
13
+ from urllib.parse import quote
14
+
15
+ from .types import QueryParams
16
+
17
+ _OFFSET = re.compile(r"^(?:UTC|GMT)?\s*([+-])(\d{1,2})(?::?(\d{2}))?$", re.IGNORECASE)
18
+
19
+
20
+ def put(query: QueryParams, key: str, value: Any) -> None:
21
+ """Set ``key`` only when ``value`` is meaningful (skips ``None`` and ``""``)."""
22
+ if value is None or value == "":
23
+ return
24
+ query[key] = value
25
+
26
+
27
+ #: The fields of a birth mapping (:class:`~lifeastroapi.types.BirthInput`).
28
+ BIRTH_FIELDS = ("date", "time", "tz", "lat", "lon")
29
+
30
+
31
+ def put_fields(
32
+ query: QueryParams,
33
+ value: Mapping[str, Any] | None,
34
+ prefix: str,
35
+ fields: tuple[str, ...] = BIRTH_FIELDS,
36
+ ) -> None:
37
+ """Copy fields of a birth mapping onto wire names: ``boy["date"]`` -> ``boy.date``."""
38
+ if value is None:
39
+ return
40
+ for name in fields:
41
+ put(query, prefix + name, value.get(name))
42
+
43
+
44
+ def build_path(template: str, values: Mapping[str, Any]) -> str:
45
+ """Fill ``{name}`` placeholders in ``template``, percent-encoding each value."""
46
+ path = template
47
+ for name, value in values.items():
48
+ if value is None or value == "":
49
+ raise ValueError(f'Missing required path parameter "{name}" for {template}')
50
+ path = path.replace("{" + name + "}", quote(_text(value), safe="!*'()"))
51
+ return path
52
+
53
+
54
+ def _text(value: Any) -> str:
55
+ if isinstance(value, bool):
56
+ return "true" if value else "false"
57
+ if isinstance(value, float) and value.is_integer() and abs(value) < 1e16:
58
+ return str(int(value))
59
+ return str(value)
60
+
61
+
62
+ def _zone(tz: str) -> tzinfo | None:
63
+ match = _OFFSET.match(tz.strip())
64
+ if match:
65
+ sign, hours, minutes = match.groups()
66
+ delta = timedelta(hours=int(hours), minutes=int(minutes or 0))
67
+ return timezone(-delta if sign == "-" else delta)
68
+ if tz.strip().upper() in ("UTC", "GMT", "Z"):
69
+ return timezone.utc
70
+ try:
71
+ from zoneinfo import ZoneInfo
72
+
73
+ return ZoneInfo(tz)
74
+ except Exception: # unknown zone, or no tz database on this machine
75
+ return None
76
+
77
+
78
+ def today_in(tz: str | None, now: datetime | None = None) -> str:
79
+ """Today's date (``YYYY-MM-DD``) in ``tz``.
80
+
81
+ The API has no "today" default: every moment endpoint rejects a request
82
+ without ``date``, so the SDK sends one. Falls back to the UTC date when
83
+ ``tz`` cannot be resolved.
84
+ """
85
+ current = now if now is not None else datetime.now(timezone.utc)
86
+ if current.tzinfo is None:
87
+ current = current.replace(tzinfo=timezone.utc)
88
+ zone = _zone(tz) if tz else None
89
+ return current.astimezone(zone or timezone.utc).strftime("%Y-%m-%d")
@@ -0,0 +1,3 @@
1
+ """SDK version, sent in the ``User-Agent`` header."""
2
+
3
+ __version__ = "0.1.0"