alfred-python 0.0.1__py3-none-any.whl → 0.4.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.
- alfred/__init__.py +1 -0
- alfred/base/__init__.py +0 -0
- alfred/base/config.py +31 -0
- alfred/base/constants.py +8 -0
- alfred/base/exceptions.py +11 -0
- alfred/http/__init__.py +0 -0
- alfred/http/http_client.py +520 -0
- alfred/http/typed.py +49 -0
- alfred/rest/__init__.py +86 -0
- alfred/rest/data_points/__init__.py +14 -0
- alfred/rest/data_points/base.py +14 -0
- alfred/rest/data_points/v1.py +21 -0
- alfred/rest/files/__init__.py +14 -0
- alfred/rest/files/base.py +51 -0
- alfred/rest/files/typed.py +71 -0
- alfred/rest/files/v1.py +84 -0
- alfred/rest/jobs/__init__.py +14 -0
- alfred/rest/jobs/base.py +24 -0
- alfred/rest/jobs/typed.py +15 -0
- alfred/rest/jobs/v1.py +32 -0
- alfred/rest/sessions/__init__.py +14 -0
- alfred/rest/sessions/base.py +20 -0
- alfred/rest/sessions/v1.py +28 -0
- alfred/typings/__init__.py +1 -0
- {app → alfred}/typings/misc.py +1 -1
- alfred/utils/__init__.py +1 -0
- {app → alfred}/utils/logging.py +29 -26
- alfred_python-0.4.0.dist-info/METADATA +283 -0
- alfred_python-0.4.0.dist-info/RECORD +32 -0
- alfred_python-0.4.0.dist-info/top_level.txt +1 -0
- alfred_python-0.0.1.dist-info/METADATA +0 -42
- alfred_python-0.0.1.dist-info/RECORD +0 -12
- alfred_python-0.0.1.dist-info/top_level.txt +0 -1
- app/__init__.py +0 -24
- app/config/__init__.py +0 -1
- app/config/settings.py +0 -21
- app/typings/__init__.py +0 -1
- app/utils/__init__.py +0 -1
- {alfred_python-0.0.1.dist-info → alfred_python-0.4.0.dist-info}/LICENSE +0 -0
- {alfred_python-0.0.1.dist-info → alfred_python-0.4.0.dist-info}/WHEEL +0 -0
alfred/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.0.1"
|
alfred/base/__init__.py
ADDED
|
File without changes
|
alfred/base/config.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Native imports
|
|
2
|
+
from typing import TypedDict, Optional, Text
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class ConfigurationDict(TypedDict):
|
|
6
|
+
base_url: Text
|
|
7
|
+
version: int
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class OverridesDict(TypedDict):
|
|
11
|
+
base_url: Optional[Text]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Configuration:
|
|
15
|
+
@staticmethod
|
|
16
|
+
def default() -> ConfigurationDict:
|
|
17
|
+
"""
|
|
18
|
+
Returns default client configuration. Currently targets Alfred V1.
|
|
19
|
+
"""
|
|
20
|
+
return Configuration.v1()
|
|
21
|
+
|
|
22
|
+
@staticmethod
|
|
23
|
+
def v1(overrides: Optional[OverridesDict] = None) -> ConfigurationDict:
|
|
24
|
+
"""
|
|
25
|
+
Returns client configuration for Alfred V1.
|
|
26
|
+
"""
|
|
27
|
+
overrides = overrides or {}
|
|
28
|
+
return {
|
|
29
|
+
"version": 1,
|
|
30
|
+
"base_url": overrides.get("base_url", "https://app.tagshelf.com"),
|
|
31
|
+
}
|
alfred/base/constants.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
class AlfredMissingAuthException(Exception):
|
|
2
|
+
"""
|
|
3
|
+
Raised when proper authentication/authorization have not been provided.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class AlfredMissingArgument(Exception):
|
|
8
|
+
"""
|
|
9
|
+
Raised when a payload is missing a required argument based on the whole context
|
|
10
|
+
of the operation.
|
|
11
|
+
"""
|
alfred/http/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,520 @@
|
|
|
1
|
+
# Native imports
|
|
2
|
+
import base64
|
|
3
|
+
import hashlib
|
|
4
|
+
import hmac
|
|
5
|
+
import os
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from typing import Dict, Any
|
|
8
|
+
from urllib.parse import quote
|
|
9
|
+
from time import time, sleep
|
|
10
|
+
from uuid import uuid4
|
|
11
|
+
from xml.etree import ElementTree as ET
|
|
12
|
+
|
|
13
|
+
# 3rd party imports
|
|
14
|
+
from requests import Session, Request, PreparedRequest, Response
|
|
15
|
+
from requests.adapters import HTTPAdapter
|
|
16
|
+
from urllib3.util.retry import Retry
|
|
17
|
+
|
|
18
|
+
# Project imports
|
|
19
|
+
from .typed import * # pylint: disable=W0401, W0614
|
|
20
|
+
from ..base.constants import RESPONSE_TYPE_HEADER_MAPPING
|
|
21
|
+
from ..base.exceptions import AlfredMissingAuthException
|
|
22
|
+
from ..utils import logging
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class HttpClient:
|
|
26
|
+
base_url: Text
|
|
27
|
+
max_retries: int
|
|
28
|
+
timeout: float
|
|
29
|
+
session: Session
|
|
30
|
+
auth_config: AuthConfiguration
|
|
31
|
+
auth_method: Optional[AuthMethod] = None
|
|
32
|
+
token: Optional[Text] = None
|
|
33
|
+
refresh_token_retry_count: int = 0
|
|
34
|
+
response_type: ResponseType = ResponseType.JSON
|
|
35
|
+
rate_limit: Optional[Dict[str, Any]] = None
|
|
36
|
+
__initial_throttle_delay: float
|
|
37
|
+
throttle_delay: float
|
|
38
|
+
throttle_threshold: int
|
|
39
|
+
throttle_delay_backoff: float = 2
|
|
40
|
+
throttle_delay_max: float = 60
|
|
41
|
+
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
base_url: Text,
|
|
45
|
+
auth_config: AuthConfiguration,
|
|
46
|
+
config: Optional[HttpConfiguration] = None,
|
|
47
|
+
) -> None:
|
|
48
|
+
"""
|
|
49
|
+
Constructor for base HTTP client.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
- base_url: Base URL of the API.
|
|
53
|
+
- config: HTTP client configuration.
|
|
54
|
+
- config.pool_connections: If True, the requests Session will use
|
|
55
|
+
pool connections (default: True).
|
|
56
|
+
- config.timeout: Timeout for the requests in seconds. Should be higher than
|
|
57
|
+
zero (default: 5).
|
|
58
|
+
- config.max_retries: Maximum number of retries each request should
|
|
59
|
+
attempt (default: 3).
|
|
60
|
+
- config.response_type {ResponseType}: Specifies the expected format of the response data (default: JSON).
|
|
61
|
+
- config.throttle_delay: Delay in seconds to throttle requests (default: 1).
|
|
62
|
+
- config.throttle_threshold: Percentage of rate limit remaining to throttle requests (default: 20).
|
|
63
|
+
Set to 0 to disable throttling. 20 means that if the remaining rate limit is less than 20%
|
|
64
|
+
of the total rate limit, the http client will throttle the request.
|
|
65
|
+
"""
|
|
66
|
+
self.base_url = base_url
|
|
67
|
+
self.session = Session()
|
|
68
|
+
self.auth_config = auth_config
|
|
69
|
+
config = config or {}
|
|
70
|
+
|
|
71
|
+
# Initialize logger
|
|
72
|
+
self.logger = logging.getLogger("alfred-python")
|
|
73
|
+
|
|
74
|
+
# Setup retry strategy
|
|
75
|
+
self.max_retries = config.get("max_retries", 3)
|
|
76
|
+
if self.max_retries <= 0:
|
|
77
|
+
raise ValueError(
|
|
78
|
+
f"Max retries ({self.max_retries}) cannot be zero or less."
|
|
79
|
+
)
|
|
80
|
+
retry_strategy = Retry(
|
|
81
|
+
total=self.max_retries,
|
|
82
|
+
status_forcelist=[429, 500, 502, 503, 504],
|
|
83
|
+
backoff_factor=1,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
# Setup timeout
|
|
87
|
+
self.timeout = config.get("timeout", 5)
|
|
88
|
+
if self.timeout <= 0:
|
|
89
|
+
raise ValueError(f"Timeout ({self.timeout}) cannot be zero or less.")
|
|
90
|
+
|
|
91
|
+
# Set up response type
|
|
92
|
+
self.response_type = config.get("response_type", ResponseType.JSON)
|
|
93
|
+
|
|
94
|
+
# Validate that it's a valid response type.
|
|
95
|
+
if self.response_type not in RESPONSE_TYPE_HEADER_MAPPING.keys():
|
|
96
|
+
raise ValueError(f"Invalid response type: {self.response_type}")
|
|
97
|
+
|
|
98
|
+
# Setup throttle delay
|
|
99
|
+
self.throttle_delay = config.get("throttle_delay", 1)
|
|
100
|
+
self.throttle_threshold = config.get("throttle_threshold", 20)
|
|
101
|
+
self.__initial_throttle_delay = self.throttle_delay
|
|
102
|
+
|
|
103
|
+
# Setup pool connections
|
|
104
|
+
pool_size = 1
|
|
105
|
+
pool_maxsize = 1
|
|
106
|
+
if config.get("pool_connections", True):
|
|
107
|
+
pool_size = 10
|
|
108
|
+
pool_maxsize = min(32, os.cpu_count() + 4)
|
|
109
|
+
|
|
110
|
+
adapter = HTTPAdapter(
|
|
111
|
+
pool_maxsize=pool_maxsize,
|
|
112
|
+
pool_connections=pool_size,
|
|
113
|
+
max_retries=retry_strategy,
|
|
114
|
+
)
|
|
115
|
+
self.session.mount("http://", adapter)
|
|
116
|
+
self.session.mount("https://", adapter)
|
|
117
|
+
|
|
118
|
+
# Setup API key (if any)
|
|
119
|
+
self.__auth_with_api_key(self.auth_config.get("api_key"))
|
|
120
|
+
|
|
121
|
+
# Setup OAuth (if any)
|
|
122
|
+
if not self.auth_method and self.auth_config.get("oauth"):
|
|
123
|
+
self.auth_method = AuthMethod.OAUTH
|
|
124
|
+
|
|
125
|
+
# Setup HMAC
|
|
126
|
+
if not self.auth_method and self.auth_config.get("hmac"):
|
|
127
|
+
self.auth_method = AuthMethod.HMAC
|
|
128
|
+
|
|
129
|
+
if not self.auth_method:
|
|
130
|
+
raise AlfredMissingAuthException
|
|
131
|
+
|
|
132
|
+
# Setup interceptor
|
|
133
|
+
self.session.hooks["response"].append(self.__response_interceptor)
|
|
134
|
+
self.session.hooks["response"].append(self.__logger_interceptor)
|
|
135
|
+
|
|
136
|
+
def __response_interceptor(self, response: Response, *args, **kwargs):
|
|
137
|
+
"""
|
|
138
|
+
Intercepts the response and raises an exception if the status code is not 200.
|
|
139
|
+
"""
|
|
140
|
+
# Extract rate limit headers
|
|
141
|
+
self.rate_limit = {
|
|
142
|
+
"limit": int(response.headers.get("X-RateLimit-Limit", 0)),
|
|
143
|
+
"remaining": int(response.headers.get("X-RateLimit-Remaining", 0)),
|
|
144
|
+
"reset_time": datetime.utcfromtimestamp(
|
|
145
|
+
int(response.headers.get("X-RateLimit-Reset", 0))
|
|
146
|
+
),
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
# if the response is unauthorized, attempt to re-authenticate OAuth
|
|
150
|
+
if (
|
|
151
|
+
response.status_code == 401
|
|
152
|
+
and self.auth_method == AuthMethod.OAUTH
|
|
153
|
+
and self.refresh_token_retry_count == 0
|
|
154
|
+
):
|
|
155
|
+
self.refresh_token_retry_count += 1
|
|
156
|
+
self.token = None
|
|
157
|
+
self.__auth_with_oauth(response.request)
|
|
158
|
+
response = self.session.send(response.request)
|
|
159
|
+
if response.status_code != 401:
|
|
160
|
+
self.refresh_token_retry_count = 0
|
|
161
|
+
return response
|
|
162
|
+
|
|
163
|
+
def __auth_with_api_key(self, api_key: Text):
|
|
164
|
+
"""
|
|
165
|
+
Set the X-TagshelfAPI-Key header using the provided API key or a
|
|
166
|
+
default value from the environment variable.
|
|
167
|
+
|
|
168
|
+
Args:
|
|
169
|
+
- api_key: A string that represents an API key used for authentication.
|
|
170
|
+
If no value is provided, the function will attempt to retrieve the API key from
|
|
171
|
+
the environment variable.
|
|
172
|
+
"""
|
|
173
|
+
key = api_key or os.getenv("ALFRED_API_KEY")
|
|
174
|
+
if not key:
|
|
175
|
+
return
|
|
176
|
+
|
|
177
|
+
self.session.headers.update({"X-TagshelfAPI-Key": key})
|
|
178
|
+
self.auth_method = AuthMethod.API_KEY
|
|
179
|
+
|
|
180
|
+
def __auth_with_oauth(self, prepped_request: PreparedRequest):
|
|
181
|
+
"""
|
|
182
|
+
Handles authentication using OAuth by obtaining an access token and
|
|
183
|
+
setting it in the HTTP headers.
|
|
184
|
+
|
|
185
|
+
Args:
|
|
186
|
+
- prepped_request: Prepared Request object.
|
|
187
|
+
"""
|
|
188
|
+
username = self.auth_config.get("oauth", {}).get("username")
|
|
189
|
+
password = self.auth_config.get("oauth", {}).get("password")
|
|
190
|
+
if not self.token:
|
|
191
|
+
self.token = self.__get_token(username, password)
|
|
192
|
+
|
|
193
|
+
prepped_request.headers.update({"Authorization": f"Bearer {self.token}"})
|
|
194
|
+
|
|
195
|
+
def __get_token(self, username: Text, password: Text):
|
|
196
|
+
"""
|
|
197
|
+
Get access token.
|
|
198
|
+
|
|
199
|
+
Args:
|
|
200
|
+
- username: A string that represents the username used for authentication.
|
|
201
|
+
- password: A string that represents the user's password used for authentication.
|
|
202
|
+
"""
|
|
203
|
+
data = {"grant_type": "password", "username": username, "password": password}
|
|
204
|
+
headers = {"Content-Type": "application/x-www-form-urlencoded"}
|
|
205
|
+
|
|
206
|
+
_, response = self.request(
|
|
207
|
+
HttpMethod.POST,
|
|
208
|
+
"/token",
|
|
209
|
+
data=data,
|
|
210
|
+
headers=headers,
|
|
211
|
+
skip_auth=True,
|
|
212
|
+
)
|
|
213
|
+
response_json = response.json()
|
|
214
|
+
return response_json.get("access_token")
|
|
215
|
+
|
|
216
|
+
def __auth_with_hmac(self, prepped_request: PreparedRequest):
|
|
217
|
+
"""
|
|
218
|
+
Generates a HMAC-based authentication header for API requests using provided
|
|
219
|
+
API key and secret key.
|
|
220
|
+
|
|
221
|
+
Args:
|
|
222
|
+
- prepped_request: Prepared Request object.
|
|
223
|
+
"""
|
|
224
|
+
api_key = self.auth_config.get("hmac", {}).get("api_key")
|
|
225
|
+
secret_key = self.auth_config.get("hmac", {}).get("secret_key")
|
|
226
|
+
|
|
227
|
+
nonce = str(uuid4())
|
|
228
|
+
request_uri = quote(prepped_request.url, safe="").lower()
|
|
229
|
+
request_method = prepped_request.method.upper()
|
|
230
|
+
request_timestamp = str(int(time()))
|
|
231
|
+
request_content = ""
|
|
232
|
+
|
|
233
|
+
if prepped_request.body:
|
|
234
|
+
md5_hash = hashlib.md5()
|
|
235
|
+
md5_hash.update(prepped_request.body.encode("utf-8"))
|
|
236
|
+
request_content = base64.b64encode(md5_hash.digest()).decode("utf-8")
|
|
237
|
+
|
|
238
|
+
# Prepare the signature
|
|
239
|
+
signature_raw_data = (
|
|
240
|
+
secret_key
|
|
241
|
+
+ request_method
|
|
242
|
+
+ request_uri
|
|
243
|
+
+ request_timestamp
|
|
244
|
+
+ nonce
|
|
245
|
+
+ request_content
|
|
246
|
+
)
|
|
247
|
+
signature = signature_raw_data.encode("utf-8")
|
|
248
|
+
|
|
249
|
+
# Create HMAC signature
|
|
250
|
+
secret_byte_array = base64.b64decode(api_key)
|
|
251
|
+
hmac_signature = hmac.new(secret_byte_array, signature, hashlib.sha256).digest()
|
|
252
|
+
signature_base64 = base64.b64encode(hmac_signature).decode("utf-8")
|
|
253
|
+
|
|
254
|
+
# Prepare the Authorization header
|
|
255
|
+
hmac_key = f"amx {secret_key}:{signature_base64}:{nonce}:{request_timestamp}"
|
|
256
|
+
prepped_request.headers.update({"Authorization": hmac_key})
|
|
257
|
+
|
|
258
|
+
def __get_headers(self, headers: Optional[Dict[str, str]]) -> Dict[str, str]:
|
|
259
|
+
"""
|
|
260
|
+
Get the request headers.
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
- headers: HTTP headers
|
|
264
|
+
"""
|
|
265
|
+
headers = headers or {}
|
|
266
|
+
default_headers = {
|
|
267
|
+
"Accept-Charset": "utf-8",
|
|
268
|
+
"Content-Type": "application/json",
|
|
269
|
+
"Accept": RESPONSE_TYPE_HEADER_MAPPING.get(self.response_type),
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
return {**default_headers, **headers}
|
|
273
|
+
|
|
274
|
+
@staticmethod
|
|
275
|
+
def __parse_response(response: Response):
|
|
276
|
+
"""
|
|
277
|
+
Parse the response based on the response type.
|
|
278
|
+
|
|
279
|
+
Args:
|
|
280
|
+
- response: HTTP response
|
|
281
|
+
"""
|
|
282
|
+
|
|
283
|
+
# Get the response type based on the content type header.
|
|
284
|
+
content_type = response.headers.get("Content-Type").split(";")[0]
|
|
285
|
+
reversed_response_type_header_mapping = {
|
|
286
|
+
v: k for k, v in RESPONSE_TYPE_HEADER_MAPPING.items()
|
|
287
|
+
}
|
|
288
|
+
response_type = reversed_response_type_header_mapping.get(content_type)
|
|
289
|
+
|
|
290
|
+
try:
|
|
291
|
+
if response_type == ResponseType.XML:
|
|
292
|
+
return ET.fromstring(response.text)
|
|
293
|
+
elif response_type == ResponseType.JSON:
|
|
294
|
+
return response.json()
|
|
295
|
+
elif response_type == ResponseType.TEXT:
|
|
296
|
+
return response.text
|
|
297
|
+
else:
|
|
298
|
+
return response.text
|
|
299
|
+
except Exception as e:
|
|
300
|
+
raise ValueError(f"Failed to parse response: {e}")
|
|
301
|
+
|
|
302
|
+
def request(
|
|
303
|
+
self,
|
|
304
|
+
method: HttpMethod,
|
|
305
|
+
uri: Text,
|
|
306
|
+
params: Optional[Dict[str, object]] = None,
|
|
307
|
+
data: Optional[Dict[str, object]] = None,
|
|
308
|
+
headers: Optional[Dict[str, str]] = None,
|
|
309
|
+
files: Optional[Dict[str, Any]] = None,
|
|
310
|
+
timeout: Optional[float] = None,
|
|
311
|
+
skip_auth: Optional[bool] = False,
|
|
312
|
+
):
|
|
313
|
+
"""
|
|
314
|
+
Makes a request to the Alfred API using the configured HTTP client.
|
|
315
|
+
|
|
316
|
+
Args:
|
|
317
|
+
- method: HTTP method.
|
|
318
|
+
- uri: Fully qualified URI.
|
|
319
|
+
- params: Query string parameters.
|
|
320
|
+
- data: Body data.
|
|
321
|
+
- headers: HTTP headers.
|
|
322
|
+
- timeout: Timeout for the requests in seconds.
|
|
323
|
+
"""
|
|
324
|
+
if timeout is None:
|
|
325
|
+
timeout = self.timeout
|
|
326
|
+
elif timeout <= 0:
|
|
327
|
+
raise ValueError(timeout)
|
|
328
|
+
|
|
329
|
+
headers = self.__get_headers(headers)
|
|
330
|
+
url = self.base_url + uri
|
|
331
|
+
|
|
332
|
+
kwargs = {
|
|
333
|
+
"method": method.value,
|
|
334
|
+
"url": url,
|
|
335
|
+
"params": params,
|
|
336
|
+
"headers": headers,
|
|
337
|
+
"files": files,
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if headers and headers.get("Content-Type") == "application/json":
|
|
341
|
+
kwargs["json"] = data
|
|
342
|
+
else:
|
|
343
|
+
kwargs["data"] = data
|
|
344
|
+
|
|
345
|
+
request = Request(**kwargs)
|
|
346
|
+
prepped_request = self.session.prepare_request(request)
|
|
347
|
+
|
|
348
|
+
if not skip_auth:
|
|
349
|
+
if self.auth_method == AuthMethod.OAUTH:
|
|
350
|
+
self.__auth_with_oauth(prepped_request)
|
|
351
|
+
|
|
352
|
+
elif self.auth_method == AuthMethod.HMAC:
|
|
353
|
+
self.__auth_with_hmac(prepped_request)
|
|
354
|
+
|
|
355
|
+
self.throttle_request(self.throttle_delay)
|
|
356
|
+
|
|
357
|
+
response = self.session.send(prepped_request, timeout=timeout)
|
|
358
|
+
|
|
359
|
+
response.raise_for_status()
|
|
360
|
+
return self.__parse_response(response), response
|
|
361
|
+
|
|
362
|
+
def get(
|
|
363
|
+
self,
|
|
364
|
+
uri: Text,
|
|
365
|
+
params: Optional[Dict[str, object]] = None,
|
|
366
|
+
data: Optional[Dict[str, object]] = None,
|
|
367
|
+
headers: Optional[Dict[str, str]] = None,
|
|
368
|
+
files: Optional[Dict[str, Any]] = None,
|
|
369
|
+
timeout: Optional[float] = None,
|
|
370
|
+
):
|
|
371
|
+
"""
|
|
372
|
+
Makes a GET request to the Alfred API.
|
|
373
|
+
|
|
374
|
+
Args:
|
|
375
|
+
- uri: Fully qualified URI.
|
|
376
|
+
- params: Query string parameters.
|
|
377
|
+
- data: Body data.
|
|
378
|
+
- headers: HTTP headers.
|
|
379
|
+
- files: Files to upload.
|
|
380
|
+
- timeout: Timeout for the requests in seconds.
|
|
381
|
+
"""
|
|
382
|
+
return self.request(HttpMethod.GET, uri, params, data, headers, files, timeout)
|
|
383
|
+
|
|
384
|
+
def post(
|
|
385
|
+
self,
|
|
386
|
+
uri: Text,
|
|
387
|
+
params: Optional[Dict[str, object]] = None,
|
|
388
|
+
data: Optional[Dict[str, object]] = None,
|
|
389
|
+
headers: Optional[Dict[str, str]] = None,
|
|
390
|
+
files: Optional[Dict[str, Any]] = None,
|
|
391
|
+
timeout: Optional[float] = None,
|
|
392
|
+
):
|
|
393
|
+
"""
|
|
394
|
+
Makes a POST request to the Alfred API.
|
|
395
|
+
|
|
396
|
+
Args:
|
|
397
|
+
- uri: Fully qualified URI.
|
|
398
|
+
- params: Query string parameters.
|
|
399
|
+
- data: Body data.
|
|
400
|
+
- headers: HTTP headers.
|
|
401
|
+
- files: Files to upload.
|
|
402
|
+
- timeout: Timeout for the requests in seconds.
|
|
403
|
+
"""
|
|
404
|
+
return self.request(HttpMethod.POST, uri, params, data, headers, files, timeout)
|
|
405
|
+
|
|
406
|
+
def put(
|
|
407
|
+
self,
|
|
408
|
+
uri: Text,
|
|
409
|
+
params: Optional[Dict[str, object]] = None,
|
|
410
|
+
data: Optional[Dict[str, object]] = None,
|
|
411
|
+
headers: Optional[Dict[str, str]] = None,
|
|
412
|
+
files: Optional[Dict[str, Any]] = None,
|
|
413
|
+
timeout: Optional[float] = None,
|
|
414
|
+
):
|
|
415
|
+
"""
|
|
416
|
+
Makes a PUT request to the Alfred API.
|
|
417
|
+
|
|
418
|
+
Args:
|
|
419
|
+
- uri: Fully qualified URI.
|
|
420
|
+
- params: Query string parameters.
|
|
421
|
+
- data: Body data.
|
|
422
|
+
- headers: HTTP headers.
|
|
423
|
+
- files: Files to upload.
|
|
424
|
+
- timeout: Timeout for the requests in seconds.
|
|
425
|
+
"""
|
|
426
|
+
return self.request(HttpMethod.PUT, uri, params, data, headers, files, timeout)
|
|
427
|
+
|
|
428
|
+
def delete(
|
|
429
|
+
self,
|
|
430
|
+
uri: Text,
|
|
431
|
+
params: Optional[Dict[str, object]] = None,
|
|
432
|
+
data: Optional[Dict[str, object]] = None,
|
|
433
|
+
headers: Optional[Dict[str, str]] = None,
|
|
434
|
+
files: Optional[Dict[str, Any]] = None,
|
|
435
|
+
timeout: Optional[float] = None,
|
|
436
|
+
):
|
|
437
|
+
"""
|
|
438
|
+
Makes a DELETE request to the Alfred API.
|
|
439
|
+
|
|
440
|
+
Args:
|
|
441
|
+
- uri: Fully qualified URI.
|
|
442
|
+
- params: Query string parameters.
|
|
443
|
+
- data: Body data.
|
|
444
|
+
- headers: HTTP headers.
|
|
445
|
+
- files: Files to upload.
|
|
446
|
+
- timeout: Timeout for the requests in seconds.
|
|
447
|
+
"""
|
|
448
|
+
return self.request(
|
|
449
|
+
HttpMethod.DELETE, uri, params, data, headers, files, timeout
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
def should_throttle(self) -> bool:
|
|
453
|
+
"""
|
|
454
|
+
Check if the client should throttle requests based on rate limiting headers.
|
|
455
|
+
"""
|
|
456
|
+
|
|
457
|
+
# We should throttle if the remaining rate limit is less than the threshold in percentage.
|
|
458
|
+
# For example, if the rate limit is 100 and the remaining is 20, we should throttle.
|
|
459
|
+
# If the rate limit is 100 and the remaining is 80, we should not throttle.
|
|
460
|
+
if self.rate_limit and self.throttle_threshold > 0:
|
|
461
|
+
remaining = self.rate_limit.get("remaining", 0)
|
|
462
|
+
limit = self.rate_limit.get("limit", 0)
|
|
463
|
+
|
|
464
|
+
if remaining <= 0:
|
|
465
|
+
self.throttle_delay = min(self.throttle_delay * self.throttle_delay_backoff, self.throttle_delay_max)
|
|
466
|
+
return True
|
|
467
|
+
else:
|
|
468
|
+
# Reset the throttle delay in case the rate limit has been reset.
|
|
469
|
+
self.throttle_delay = self.__initial_throttle_delay
|
|
470
|
+
|
|
471
|
+
# Check if the remaining rate limit is less than the threshold.
|
|
472
|
+
return (remaining / limit) * 100 <= self.throttle_threshold
|
|
473
|
+
return False
|
|
474
|
+
|
|
475
|
+
def throttle_request(self, delay: float = 1.0):
|
|
476
|
+
"""
|
|
477
|
+
Throttle the request by delaying for a given time.
|
|
478
|
+
"""
|
|
479
|
+
if self.should_throttle():
|
|
480
|
+
logging.warning("Rate limit is close to being reached. Throttling request.")
|
|
481
|
+
sleep(delay)
|
|
482
|
+
|
|
483
|
+
def __logger_interceptor(self, response: Response, *args, **kwargs):
|
|
484
|
+
"""
|
|
485
|
+
Log the HTTP status code and response body of erroneous responses.
|
|
486
|
+
"""
|
|
487
|
+
|
|
488
|
+
# Log detailed HTTP request information.
|
|
489
|
+
body = (
|
|
490
|
+
response.request.body
|
|
491
|
+
if not isinstance(response.request.body, bytes)
|
|
492
|
+
else ""
|
|
493
|
+
)
|
|
494
|
+
self.logger.debug(
|
|
495
|
+
{
|
|
496
|
+
"message": "HTTP request details.",
|
|
497
|
+
"method": response.request.method,
|
|
498
|
+
"url": response.request.url,
|
|
499
|
+
"headers": {
|
|
500
|
+
k: v
|
|
501
|
+
for k, v in response.request.headers.items()
|
|
502
|
+
if k.lower() not in ["authorization", "cookie", "x-tagshelfapi-key"]
|
|
503
|
+
},
|
|
504
|
+
"body": body,
|
|
505
|
+
}
|
|
506
|
+
)
|
|
507
|
+
|
|
508
|
+
# Log response details if not successful.
|
|
509
|
+
if not response.ok:
|
|
510
|
+
self.logger.debug(
|
|
511
|
+
{
|
|
512
|
+
"message": "HTTP response details.",
|
|
513
|
+
"method": response.request.method,
|
|
514
|
+
"url": response.request.url,
|
|
515
|
+
"status_code": response.status_code,
|
|
516
|
+
"body": response.text,
|
|
517
|
+
"response_size": len(response.content),
|
|
518
|
+
"response_content_type": response.headers.get("Content-Type"),
|
|
519
|
+
}
|
|
520
|
+
)
|
alfred/http/typed.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# Native imports
|
|
2
|
+
from enum import Enum
|
|
3
|
+
from typing import TypedDict, Optional, Text
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class HttpMethod(Enum):
|
|
7
|
+
POST = "POST"
|
|
8
|
+
GET = "GET"
|
|
9
|
+
PUT = "PUT"
|
|
10
|
+
PATCH = "PATCH"
|
|
11
|
+
DELETE = "DELETE"
|
|
12
|
+
HEAD = "HEAD"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AuthMethod(Enum):
|
|
16
|
+
API_KEY = ("apikey",)
|
|
17
|
+
OAUTH = ("oauth",)
|
|
18
|
+
HMAC = ("hmac",)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ResponseType:
|
|
22
|
+
JSON = "json"
|
|
23
|
+
TEXT = "text"
|
|
24
|
+
XML = "xml"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class OAuthConfiguration(TypedDict):
|
|
28
|
+
username: Text
|
|
29
|
+
password: Text
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class HmacConfiguration(TypedDict):
|
|
33
|
+
api_key: Text
|
|
34
|
+
secret_key: Text
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class AuthConfiguration(TypedDict):
|
|
38
|
+
api_key: Optional[Text]
|
|
39
|
+
oauth: Optional[OAuthConfiguration]
|
|
40
|
+
hmac: Optional[HmacConfiguration]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class HttpConfiguration(TypedDict):
|
|
44
|
+
pool_connections: Optional[bool]
|
|
45
|
+
timeout: Optional[float]
|
|
46
|
+
max_retries: Optional[int]
|
|
47
|
+
response_type: Optional[ResponseType]
|
|
48
|
+
throttle_delay: Optional[float]
|
|
49
|
+
throttle_threshold: Optional[int]
|