-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_client.py
More file actions
210 lines (169 loc) · 6.27 KB
/
http_client.py
File metadata and controls
210 lines (169 loc) · 6.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
"""Core HTTP client with retry logic and authentication."""
from __future__ import annotations
import os
import time
from typing import Any, Literal
import httpx
from astroapi.errors import AstrologyError
from astroapi.types.config import AstrologyClientConfig, RetryConfig
class HttpClient:
"""HTTP client with retry logic, timeout, and authentication.
Handles:
- Bearer token authentication
- Automatic retry for transient failures
- Response envelope unwrapping
- Debug logging
- Error handling and conversion
"""
def __init__(self, config: AstrologyClientConfig) -> None:
"""Initialize HTTP client.
Args:
config: Client configuration
Raises:
AstrologyError: If API key is not provided
"""
self.config = config
self.client = httpx.Client(
base_url=config.base_url,
timeout=config.timeout,
headers=self._build_auth_headers(),
)
def _build_auth_headers(self) -> dict[str, str]:
"""Build authentication headers.
Returns:
Dictionary with Authorization header
Raises:
AstrologyError: If API key is not provided
"""
api_key = self.config.api_key or os.environ.get("ASTROLOGY_API_KEY")
if not api_key:
raise AstrologyError(
"API key required (provide in config or set ASTROLOGY_API_KEY environment variable)"
)
return {"Authorization": f"Bearer {api_key}"}
def _log(self, message: str, details: Any = None) -> None:
"""Log debug message if debug mode is enabled.
Args:
message: Log message
details: Optional additional details
"""
if self.config.debug:
if self.config.logger:
self.config.logger(message, details)
else:
details_str = f" {details}" if details else ""
print(f"[astroapi] {message}{details_str}")
def _unwrap_payload(self, payload: dict[str, Any]) -> Any:
"""Unwrap response envelope if present.
API responses may be wrapped in {data: ...} or {result: ...} envelopes.
This method extracts the actual payload.
Args:
payload: Response payload dictionary
Returns:
Unwrapped payload (dict, list, or primitive)
"""
if "data" in payload:
return payload["data"]
if "result" in payload:
return payload["result"]
return payload
def _request_with_retry(
self,
method: str,
url: str,
response_type: Literal["json", "text"] = "json",
**kwargs: Any,
) -> Any:
"""Make HTTP request with retry logic.
Args:
method: HTTP method (GET, POST, etc.)
url: Request URL
response_type: Expected response type ('json' or 'text')
**kwargs: Additional arguments passed to httpx.request
Returns:
Response data (dict for JSON, str for text)
Raises:
AstrologyError: If request fails after all retries
"""
retry_config = self.config.retry or RetryConfig(attempts=0)
attempt = 0
while True:
try:
self._log(f"{method.upper()} {url}", kwargs)
response = self.client.request(method, url, **kwargs)
# Check for retryable status codes
if (
response.status_code in retry_config.retry_status_codes
and attempt < retry_config.attempts
):
attempt += 1
delay_seconds = retry_config.delay_ms / 1000.0
self._log(
f"Retry attempt {attempt}/{retry_config.attempts} "
f"(status {response.status_code})",
f"waiting {delay_seconds}s",
)
time.sleep(delay_seconds)
continue
response.raise_for_status()
if response_type == "text":
return response.text
payload = response.json()
return self._unwrap_payload(payload)
except httpx.HTTPStatusError as e:
raise AstrologyError.from_response(e.response) from e
except httpx.RequestError as e:
# Network errors
if attempt < retry_config.attempts:
attempt += 1
delay_seconds = retry_config.delay_ms / 1000.0
self._log(
f"Retry attempt {attempt}/{retry_config.attempts} (network error)",
str(e),
)
time.sleep(delay_seconds)
continue
raise AstrologyError(str(e), code="NETWORK_ERROR") from e
def get(
self,
url: str,
params: dict[str, Any] | None = None,
response_type: Literal["json", "text"] = "json",
) -> Any:
"""Make GET request.
Args:
url: Request URL
params: Query parameters
response_type: Expected response type ('json' or 'text')
Returns:
Response data
Raises:
AstrologyError: If request fails
"""
return self._request_with_retry("GET", url, response_type=response_type, params=params)
def post(
self,
url: str,
json: dict[str, Any] | None = None,
response_type: Literal["json", "text"] = "json",
) -> Any:
"""Make POST request.
Args:
url: Request URL
json: JSON request body
response_type: Expected response type ('json' or 'text')
Returns:
Response data
Raises:
AstrologyError: If request fails
"""
return self._request_with_retry("POST", url, response_type=response_type, json=json)
def close(self) -> None:
"""Close HTTP client and release resources."""
self.client.close()
def __enter__(self) -> HttpClient:
"""Context manager entry."""
return self
def __exit__(self, *args: Any) -> None:
"""Context manager exit."""
self.close()