PyFlumeNG 0.9.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.
@@ -0,0 +1,138 @@
1
+ """Retrieve notifications from Flume API."""
2
+
3
+ from typing import Any, List, Optional, Union, cast
4
+
5
+ from requests import Session
6
+
7
+ from .auth import FlumeAuth, FlumePortalAuth # noqa: WPS300
8
+ from .constants import ( # noqa: WPS300
9
+ API_BASE_URL,
10
+ API_NOTIFICATIONS_URL,
11
+ DEFAULT_TIMEOUT,
12
+ )
13
+ from .models import Notification, modelize # noqa: WPS300
14
+ from .types import JSONDict, RequestParams # noqa: WPS300
15
+ from .utils import configure_logger, flume_response_error # noqa: WPS300
16
+
17
+ # Configure logging
18
+ LOGGER = configure_logger(__name__)
19
+
20
+
21
+ class FlumeNotificationList:
22
+ """Get Flume Notifications list from API."""
23
+
24
+ def __init__( # noqa: WPS211
25
+ self,
26
+ flume_auth: Union[FlumeAuth, FlumePortalAuth],
27
+ http_session: Optional[Session] = None,
28
+ timeout: float = DEFAULT_TIMEOUT,
29
+ read: str = "false",
30
+ sort_direction: str = "ASC",
31
+ ) -> None:
32
+ """
33
+ Initialize the FlumeNotificationList object.
34
+
35
+ Args:
36
+ flume_auth: Authentication object.
37
+ http_session: Optional Requests Session().
38
+ timeout: Requests timeout for throttling, default DEFAULT_TIMEOUT.
39
+ read: state of notification list, default "false".
40
+ sort_direction: Which direction to sort notifications on, default "ASC".
41
+ """
42
+ self._timeout: float = timeout
43
+ self._flume_auth: Union[FlumeAuth, FlumePortalAuth] = flume_auth
44
+ self._read: str = read
45
+ self._sort_direction: str = sort_direction
46
+ self._http_session: Session = http_session or Session()
47
+ self.has_next: bool = False
48
+ self.next_page: Optional[str] = None
49
+ self.notification_list: List[Notification] = self.get_notifications()
50
+
51
+ def get_notifications(self) -> List[Notification]:
52
+ """Return all notifications from devices owned by the user.
53
+
54
+ Returns:
55
+ List[Notification]: Typed notification models.
56
+ """
57
+
58
+ api_url = API_NOTIFICATIONS_URL.format(user_id=self._flume_auth.user_id)
59
+
60
+ query_string: RequestParams = {
61
+ "limit": "50",
62
+ "offset": "0",
63
+ "sort_direction": self._sort_direction,
64
+ "read": self._read,
65
+ }
66
+
67
+ return self._get_notification_request(api_url, query_string)
68
+
69
+ def get_next_notifications(self) -> List[Notification]:
70
+ """Return next page of notification from devices owned by the user.
71
+
72
+ Returns:
73
+ Returns JSON list of notifications.
74
+
75
+ Raises:
76
+ ValueError: If no next page is available.
77
+ """
78
+ if self.has_next:
79
+ api_url = f"{API_BASE_URL}{self.next_page}"
80
+ query_string: RequestParams = {}
81
+ else:
82
+ raise ValueError("No next page available.")
83
+ return self._get_notification_request(api_url, query_string)
84
+
85
+ def _has_next_page(self, response_json: Optional[JSONDict]) -> bool:
86
+ """Return True if the next page exists.
87
+
88
+ Args:
89
+ response_json (Object): Response from API.
90
+
91
+ Returns:
92
+ Boolean: Returns true if next page exists, False if not.
93
+ """
94
+ if response_json is None:
95
+ return False
96
+ pagination = response_json.get("pagination")
97
+ return isinstance(pagination, dict) and pagination.get("next") is not None
98
+
99
+ def _get_notification_request(
100
+ self,
101
+ api_url: str,
102
+ query_string: RequestParams,
103
+ ) -> List[Notification]:
104
+ """Make an API request to get usage alerts from the Flume API.
105
+
106
+ Args:
107
+ api_url (string): URL for request
108
+ query_string (object): query string options
109
+
110
+ Returns:
111
+ object: Reponse in JSON format from API.
112
+ """
113
+
114
+ response = self._http_session.request(
115
+ "GET",
116
+ api_url,
117
+ headers=self._flume_auth.authorization_header,
118
+ params=cast(Any, query_string),
119
+ timeout=self._timeout,
120
+ )
121
+
122
+ LOGGER.debug(f"_get_notification_request Response: {response.text}")
123
+
124
+ # Check for response errors.
125
+ flume_response_error("Impossible to retrieve notifications", response)
126
+
127
+ response_json = response.json()
128
+ if self._has_next_page(response_json):
129
+ self.next_page = response_json["pagination"]["next"]
130
+ self.has_next = True
131
+ LOGGER.debug(
132
+ f"Next page for Notification results: {self.next_page}",
133
+ )
134
+ else:
135
+ self.has_next = False
136
+ self.next_page = None
137
+ LOGGER.debug("No further pages for Notification results.")
138
+ return modelize(response_json["data"], Notification)
pyflume/py.typed ADDED
@@ -0,0 +1 @@
1
+
pyflume/rate_limit.py ADDED
@@ -0,0 +1,52 @@
1
+ """Rate-limit state for Flume authentication and API responses."""
2
+
3
+ from datetime import datetime, timezone
4
+ from typing import Dict, Mapping, Optional, Union
5
+
6
+
7
+ class RateLimitState:
8
+ """Track a baseline and the latest server-advertised quota."""
9
+
10
+ def __init__(self, baseline: int) -> None:
11
+ self.baseline: int = baseline
12
+ self.limit: int = baseline
13
+ self.remaining: Optional[int] = None
14
+ self.reset: Optional[int] = None
15
+ self.retry_after: Optional[str] = None
16
+
17
+ @property
18
+ def reset_at(self) -> Optional[datetime]:
19
+ """Return reset time as a UTC datetime, if available."""
20
+ if self.reset is None:
21
+ return None
22
+ return datetime.fromtimestamp(self.reset, timezone.utc)
23
+
24
+ def update_from_headers(self, headers: Mapping[str, str]) -> None:
25
+ """Update values from standard Flume rate-limit headers."""
26
+ numeric_headers = {
27
+ "limit": headers.get("X-RateLimit-Limit"),
28
+ "remaining": headers.get("X-RateLimit-Remaining"),
29
+ "reset": headers.get("X-RateLimit-Reset"),
30
+ }
31
+ for key, raw_value in numeric_headers.items():
32
+ if raw_value is None:
33
+ continue
34
+ try:
35
+ value = int(raw_value)
36
+ except ValueError:
37
+ continue
38
+ setattr(self, key, value)
39
+
40
+ retry_after = headers.get("Retry-After")
41
+ if retry_after is not None:
42
+ self.retry_after = retry_after
43
+
44
+ def to_dict(self) -> Dict[str, Optional[Union[int, str]]]:
45
+ """Return serializable rate-limit state."""
46
+ return {
47
+ "baseline": self.baseline,
48
+ "limit": self.limit,
49
+ "remaining": self.remaining,
50
+ "reset": self.reset,
51
+ "retry_after": self.retry_after,
52
+ }
pyflume/types.py ADDED
@@ -0,0 +1,48 @@
1
+ """Shared public typing aliases for PyFlumeNG."""
2
+
3
+ from typing import Dict, List, Mapping, Optional, TypedDict, Union
4
+
5
+ JSONPrimitive = Union[None, bool, int, float, str]
6
+ JSONValue = Union[JSONPrimitive, List["JSONValue"], Dict[str, "JSONValue"]]
7
+ JSONDict = Dict[str, JSONValue]
8
+ JSONList = List[JSONValue]
9
+ ResourceId = Union[int, str]
10
+ RequestParams = Mapping[str, JSONValue]
11
+ QueryValues = Dict[str, Optional[float]]
12
+
13
+
14
+ class _RequiredQuerySpec(TypedDict):
15
+ """Fields required by every Flume device-query entry."""
16
+
17
+ request_id: str
18
+
19
+
20
+ class QuerySpec(_RequiredQuerySpec, total=False):
21
+ """One query in a Flume device-query payload."""
22
+
23
+ bucket: str
24
+ since_datetime: str
25
+ until_datetime: str
26
+ operation: str
27
+ units: str
28
+
29
+
30
+ class QueryPayload(TypedDict):
31
+ """Payload accepted by the legacy :class:`FlumeData` query helper."""
32
+
33
+ queries: List[QuerySpec]
34
+
35
+
36
+ class _RequiredFlumeToken(TypedDict):
37
+ """Fields every successful Flume OAuth token response must contain."""
38
+
39
+ access_token: str
40
+
41
+
42
+ class FlumeToken(_RequiredFlumeToken, total=False):
43
+ """OAuth token fields returned by Flume's Personal and Portal flows."""
44
+
45
+ refresh_token: str
46
+ token_type: str
47
+ scope: str
48
+ expires_in: int
pyflume/usage.py ADDED
@@ -0,0 +1,265 @@
1
+ """Retrieve usage alert notifications from the Flume API."""
2
+
3
+ from typing import Any, List, Optional, Type, TypeVar, Union, cast
4
+
5
+ from requests import Session
6
+
7
+ from .auth import FlumeAuth, FlumePortalAuth # noqa: WPS300
8
+ from .constants import ( # noqa: WPS300
9
+ API_BASE_URL,
10
+ API_USAGE_RULE_URL,
11
+ API_USAGE_RULES_URL,
12
+ API_USAGE_URL,
13
+ DEFAULT_TIMEOUT,
14
+ )
15
+ from .models import FlumeModel, UsageAlert, UsageAlertRule, modelize # noqa: WPS300
16
+ from .types import JSONDict, JSONValue, RequestParams, ResourceId # noqa: WPS300
17
+ from .utils import configure_logger, flume_response_error # noqa: WPS300
18
+
19
+ # Configure logging
20
+ LOGGER = configure_logger(__name__)
21
+ ModelT = TypeVar("ModelT", bound=FlumeModel)
22
+
23
+
24
+ class FlumeUsageAlertList:
25
+ """Get Flume Usage Alert list from API."""
26
+
27
+ def __init__(
28
+ self,
29
+ flume_auth: Union[FlumeAuth, FlumePortalAuth],
30
+ http_session: Optional[Session] = None,
31
+ timeout: float = DEFAULT_TIMEOUT,
32
+ read: str = "false",
33
+ ) -> None:
34
+ """
35
+
36
+ Initialize the data object.
37
+
38
+ Args:
39
+ flume_auth: Authentication object.
40
+ http_session: Requests Session()
41
+ timeout: Requests timeout for throttling.
42
+ read: state of usage alert list, have they been read, not read.
43
+
44
+ """
45
+ self._timeout: float = timeout
46
+ self._flume_auth: Union[FlumeAuth, FlumePortalAuth] = flume_auth
47
+ self._read: str = read
48
+
49
+ if http_session is None:
50
+ self._http_session: Session = Session()
51
+ else:
52
+ self._http_session = http_session
53
+
54
+ self.has_next: bool = False
55
+ self.next_page: Optional[str] = None
56
+ self.usage_alert_list: List[UsageAlert] = self.get_usage_alerts()
57
+
58
+ def get_usage_alerts(self) -> List[UsageAlert]:
59
+ """Return initial page of usage alerts from devices owned by the user.
60
+
61
+ Returns:
62
+ Returns JSON list of usage alerts.
63
+ """
64
+
65
+ api_url = API_USAGE_URL.format(user_id=self._flume_auth.user_id)
66
+ query_string: RequestParams = {
67
+ "limit": "50",
68
+ "offset": "0",
69
+ "sort_direction": "ASC",
70
+ "read": self._read,
71
+ }
72
+ return cast(List[UsageAlert], self._get_usage_request(api_url, query_string))
73
+
74
+ def get_next_usage_alerts(self) -> List[UsageAlert]:
75
+ """Return next page of usage alerts from devices owned by the user.
76
+
77
+ Returns:
78
+ Returns JSON list of usage alerts.
79
+
80
+ Raises:
81
+ ValueError: If no next page is available.
82
+ """
83
+ if self.has_next:
84
+ api_url = f"{API_BASE_URL}{self.next_page}"
85
+ query_string: RequestParams = {}
86
+ else:
87
+ raise ValueError("No next page available.")
88
+ return cast(List[UsageAlert], self._get_usage_request(api_url, query_string))
89
+
90
+ def get_usage_alert_rules(self, device_id: ResourceId) -> List[UsageAlertRule]:
91
+ """Return usage alert rules configured for a device.
92
+
93
+ Args:
94
+ device_id (string): Device ID owning the rules.
95
+
96
+ Returns:
97
+ Returns JSON list of usage alert rules.
98
+ """
99
+ api_url = API_USAGE_RULES_URL.format(
100
+ user_id=self._flume_auth.user_id,
101
+ device_id=device_id,
102
+ )
103
+ return cast(
104
+ List[UsageAlertRule],
105
+ self._get_usage_request(
106
+ api_url,
107
+ {},
108
+ update_pagination=False,
109
+ model=UsageAlertRule,
110
+ ),
111
+ )
112
+
113
+ def get_usage_alert_rule(
114
+ self,
115
+ device_id: ResourceId,
116
+ rule_id: ResourceId,
117
+ ) -> List[UsageAlertRule]:
118
+ """Return a single usage alert rule for a device.
119
+
120
+ Args:
121
+ device_id (string): Device ID owning the rule.
122
+ rule_id (string/int): Usage alert rule ID.
123
+
124
+ Returns:
125
+ Returns JSON object (or single-element list) for the rule.
126
+ """
127
+ api_url = API_USAGE_RULE_URL.format(
128
+ user_id=self._flume_auth.user_id,
129
+ device_id=device_id,
130
+ rule_id=rule_id,
131
+ )
132
+ return cast(
133
+ List[UsageAlertRule],
134
+ self._get_usage_request(
135
+ api_url,
136
+ {},
137
+ update_pagination=False,
138
+ model=UsageAlertRule,
139
+ ),
140
+ )
141
+
142
+ def update_usage_alert_rule(
143
+ self,
144
+ device_id: ResourceId,
145
+ rule_id: ResourceId,
146
+ payload: JSONDict,
147
+ ) -> JSONValue:
148
+ """Update a usage alert rule for a device.
149
+
150
+ Example:
151
+ update_usage_alert_rule(device_id, rule_id, {"active": False})
152
+
153
+ Args:
154
+ device_id (string): Device ID owning the rule.
155
+ rule_id (string/int): Usage alert rule ID.
156
+ payload (dict): Fields to patch, e.g. {"active": False}.
157
+
158
+ Returns:
159
+ object: Response data from API. Note: live API returns an empty
160
+ list on PATCH success, so re-GET the rule to verify state.
161
+ """
162
+ api_url = API_USAGE_RULE_URL.format(
163
+ user_id=self._flume_auth.user_id,
164
+ device_id=device_id,
165
+ rule_id=rule_id,
166
+ )
167
+ response = self._http_session.request(
168
+ "PATCH",
169
+ api_url,
170
+ headers=self._flume_auth.authorization_header,
171
+ json=payload,
172
+ timeout=self._timeout,
173
+ )
174
+
175
+ LOGGER.debug(f"update_usage_alert_rule Response: {response.text}")
176
+
177
+ # Check for response errors.
178
+ flume_response_error("Impossible to update usage alert rule", response)
179
+
180
+ return response.json()["data"]
181
+
182
+ def set_usage_alert_rule_active(
183
+ self,
184
+ device_id: ResourceId,
185
+ rule_id: ResourceId,
186
+ active: bool,
187
+ ) -> JSONValue:
188
+ """Enable or disable a usage alert rule for a device.
189
+
190
+ Args:
191
+ device_id (string): Device ID owning the rule.
192
+ rule_id (string/int): Usage alert rule ID.
193
+ active (bool): True to enable the rule, False to disable it.
194
+
195
+ Returns:
196
+ object: Response in JSON format from API.
197
+ """
198
+ return self.update_usage_alert_rule(
199
+ device_id,
200
+ rule_id,
201
+ {"active": bool(active)},
202
+ )
203
+
204
+ def _has_next_page(self, response_json: Optional[JSONDict]) -> bool:
205
+ """Return True if the next page exists.
206
+
207
+ Args:
208
+ response_json (Object): Response from API.
209
+
210
+ Returns:
211
+ Boolean: Returns true if next page exists, False if not.
212
+ """
213
+ if response_json is None:
214
+ return False
215
+ pagination = response_json.get("pagination")
216
+ return isinstance(pagination, dict) and pagination.get("next") is not None
217
+
218
+ def _get_usage_request(
219
+ self,
220
+ api_url: str,
221
+ query_string: RequestParams,
222
+ update_pagination: bool = True,
223
+ model: Type[FlumeModel] = UsageAlert,
224
+ ) -> List[FlumeModel]:
225
+ """Make an API request to get usage alerts from the Flume API.
226
+
227
+ Args:
228
+ api_url (string): URL for request
229
+ query_string (object): query string options
230
+ update_pagination (bool): Whether to update usage-alert list
231
+ pagination state for this request.
232
+ model (type): Model used to normalize response data.
233
+
234
+ Returns:
235
+ object: Reponse in JSON format from API.
236
+ """
237
+
238
+ response = self._http_session.request(
239
+ "GET",
240
+ api_url,
241
+ headers=self._flume_auth.authorization_header,
242
+ params=cast(Any, query_string),
243
+ timeout=self._timeout,
244
+ )
245
+
246
+ LOGGER.debug(f"_get_usage_request Response: {response.text}")
247
+
248
+ # Check for response errors.
249
+ flume_response_error("Impossible to retrieve usage alert", response)
250
+
251
+ response_json = response.json()
252
+ if not update_pagination:
253
+ return cast(List[FlumeModel], modelize(response_json["data"], model))
254
+
255
+ if self._has_next_page(response_json):
256
+ self.next_page = response_json["pagination"]["next"]
257
+ self.has_next = True
258
+ LOGGER.debug(
259
+ f"Next page for Usage results: {self.next_page}",
260
+ )
261
+ else:
262
+ self.has_next = False
263
+ self.next_page = None
264
+ LOGGER.debug("No further pages for Usage results.")
265
+ return cast(List[FlumeModel], modelize(response_json["data"], model))
pyflume/utils.py ADDED
@@ -0,0 +1,140 @@
1
+ """All functions to support Flume App."""
2
+
3
+ import json
4
+ import logging
5
+ from datetime import datetime, timedelta
6
+ from typing import Union
7
+
8
+ from requests import Response
9
+
10
+
11
+ def configure_logger(name: str) -> logging.Logger:
12
+ """Configure and return a custom logger for the given name.
13
+
14
+ Args:
15
+ name (string): Name of logger
16
+
17
+ Returns:
18
+ object: Logger Handler
19
+ """
20
+ logger = logging.getLogger(name)
21
+ logger.setLevel(logging.INFO)
22
+
23
+ logger_handler = logging.StreamHandler()
24
+ formatter = logging.Formatter(
25
+ "{asctime} - {name} - {levelname} - {message}",
26
+ style="{",
27
+ )
28
+ logger_handler.setFormatter(formatter)
29
+
30
+ logger.addHandler(logger_handler)
31
+
32
+ return logger
33
+
34
+
35
+ def format_time(time: datetime) -> str:
36
+ """
37
+ Format time based on strftime.
38
+
39
+ Args:
40
+ time: Expected time as datetime.datetime class
41
+
42
+ Returns:
43
+ Formatted time.
44
+
45
+ """
46
+ return time.replace(second=0).strftime("%Y-%m-%d %H:%M:%S") # noqa: WPS323
47
+
48
+
49
+ def format_start_today(time: datetime) -> str:
50
+ """
51
+ Format time starting at 00:00:00 provided datetime.
52
+
53
+ Args:
54
+ time: Expected time as datetime.datetime class
55
+
56
+ Returns:
57
+ Formatted time.
58
+
59
+ """
60
+ return format_time(datetime.combine(time, datetime.min.time()))
61
+
62
+
63
+ def format_start_month(time: datetime) -> str:
64
+ """
65
+ Format time starting at the first of the month for provided datetime.
66
+
67
+ Args:
68
+ time: Expected time as datetime.datetime class
69
+
70
+ Returns:
71
+ Formatted time.
72
+
73
+ """
74
+ return format_time(
75
+ datetime.combine(
76
+ time.replace(day=1),
77
+ datetime.min.time(),
78
+ ),
79
+ )
80
+
81
+
82
+ def format_start_week(time: datetime) -> str:
83
+ """
84
+ Format time starting at the start of week for provided datetime.
85
+
86
+ Args:
87
+ time: Expected time as datetime.datetime class
88
+
89
+ Returns:
90
+ Formatted time.
91
+
92
+ """
93
+ return format_time(
94
+ datetime.combine(
95
+ time - timedelta(days=time.weekday()),
96
+ datetime.min.time(),
97
+ ),
98
+ )
99
+
100
+
101
+ class FlumeResponseError(Exception):
102
+ """
103
+ Exception raised for errors in the Flume response.
104
+
105
+ Attributes:
106
+ message -- explanation of the error
107
+ """
108
+
109
+
110
+ def flume_response_error(message: str, response: Response) -> None:
111
+ """Define a function to handle response errors from the Flume API.
112
+
113
+ Args:
114
+ message (string): Message received as error
115
+ response (string): Response received as error
116
+
117
+ Raises:
118
+ FlumeResponseError: Exception raised when the status code is not 200.
119
+ """
120
+ # If the response code is 200 (OK), no error has occurred, so return immediately
121
+ if response.status_code == 200: # noqa: WPS432
122
+ return
123
+
124
+ # If the response code is 400 (Bad Request), retrieve the detailed error message
125
+ if response.status_code == 400: # noqa: WPS432
126
+ error_message: Union[str, int, float, bool, None] = json.loads(response.text)[
127
+ "detailed"
128
+ ][0]
129
+ else:
130
+ # For other error codes, retrieve the general error message
131
+ error_message = json.loads(response.text)["message"]
132
+
133
+ # Raise a custom exception with a formatted message containing the error details
134
+ raise FlumeResponseError(
135
+ "Message:{0}.\nResponse code returned:{1}.\nError message returned:{2}.".format(
136
+ message,
137
+ response.status_code,
138
+ error_message,
139
+ ),
140
+ )