automizor 0.4.15__tar.gz → 0.4.17__tar.gz

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 (32) hide show
  1. {automizor-0.4.15/automizor.egg-info → automizor-0.4.17}/PKG-INFO +11 -2
  2. automizor-0.4.17/automizor/__init__.py +18 -0
  3. {automizor-0.4.15 → automizor-0.4.17}/automizor/action/_action.py +5 -12
  4. {automizor-0.4.15 → automizor-0.4.17}/automizor/datastore/_datastore.py +11 -21
  5. automizor-0.4.17/automizor/exceptions.py +118 -0
  6. {automizor-0.4.15 → automizor-0.4.17}/automizor/job/_job.py +5 -12
  7. {automizor-0.4.15 → automizor-0.4.17}/automizor/storage/_storage.py +47 -91
  8. {automizor-0.4.15 → automizor-0.4.17}/automizor/vault/_vault.py +17 -36
  9. {automizor-0.4.15 → automizor-0.4.17}/automizor/workflow/_workflow.py +11 -17
  10. {automizor-0.4.15 → automizor-0.4.17/automizor.egg-info}/PKG-INFO +11 -2
  11. {automizor-0.4.15 → automizor-0.4.17}/automizor.egg-info/SOURCES.txt +0 -2
  12. automizor-0.4.15/automizor/__init__.py +0 -1
  13. automizor-0.4.15/automizor/exceptions.py +0 -69
  14. automizor-0.4.15/automizor/log/__init__.py +0 -95
  15. automizor-0.4.15/automizor/log/_log.py +0 -97
  16. {automizor-0.4.15 → automizor-0.4.17}/LICENSE +0 -0
  17. {automizor-0.4.15 → automizor-0.4.17}/MANIFEST.in +0 -0
  18. {automizor-0.4.15 → automizor-0.4.17}/README.md +0 -0
  19. {automizor-0.4.15 → automizor-0.4.17}/automizor/action/__init__.py +0 -0
  20. {automizor-0.4.15 → automizor-0.4.17}/automizor/datastore/__init__.py +0 -0
  21. {automizor-0.4.15 → automizor-0.4.17}/automizor/datastore/_container.py +0 -0
  22. {automizor-0.4.15 → automizor-0.4.17}/automizor/job/__init__.py +0 -0
  23. {automizor-0.4.15 → automizor-0.4.17}/automizor/storage/__init__.py +0 -0
  24. {automizor-0.4.15 → automizor-0.4.17}/automizor/utils.py +0 -0
  25. {automizor-0.4.15 → automizor-0.4.17}/automizor/vault/__init__.py +0 -0
  26. {automizor-0.4.15 → automizor-0.4.17}/automizor/vault/_container.py +0 -0
  27. {automizor-0.4.15 → automizor-0.4.17}/automizor/workflow/__init__.py +0 -0
  28. {automizor-0.4.15 → automizor-0.4.17}/automizor.egg-info/dependency_links.txt +0 -0
  29. {automizor-0.4.15 → automizor-0.4.17}/automizor.egg-info/requires.txt +0 -0
  30. {automizor-0.4.15 → automizor-0.4.17}/automizor.egg-info/top_level.txt +0 -0
  31. {automizor-0.4.15 → automizor-0.4.17}/setup.cfg +0 -0
  32. {automizor-0.4.15 → automizor-0.4.17}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: automizor
3
- Version: 0.4.15
3
+ Version: 0.4.17
4
4
  Summary: Python Automizor framework
5
5
  Home-page: https://github.com/automizor/automizor-python
6
6
  Author: Christian Fischer
@@ -16,3 +16,12 @@ Classifier: Programming Language :: Python :: 3.11
16
16
  Classifier: Programming Language :: Python :: 3.12
17
17
  License-File: LICENSE
18
18
  Requires-Dist: requests
19
+ Dynamic: author
20
+ Dynamic: author-email
21
+ Dynamic: classifier
22
+ Dynamic: home-page
23
+ Dynamic: keywords
24
+ Dynamic: license
25
+ Dynamic: license-file
26
+ Dynamic: requires-dist
27
+ Dynamic: summary
@@ -0,0 +1,18 @@
1
+ import requests
2
+ from requests.adapters import HTTPAdapter
3
+ from urllib3.util.retry import Retry
4
+
5
+ retry_strategy = Retry(
6
+ total=6,
7
+ backoff_factor=1,
8
+ status_forcelist=[429, 500, 502, 503, 504, 520, 521, 522, 523, 524],
9
+ allowed_methods=["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"],
10
+ raise_on_status=False,
11
+ )
12
+
13
+ adapter = HTTPAdapter(max_retries=retry_strategy)
14
+ session = requests.Session()
15
+ session.mount("https://", adapter)
16
+ session.mount("http://", adapter)
17
+
18
+ version = "0.4.17"
@@ -1,7 +1,6 @@
1
1
  from typing import Optional
2
2
 
3
- import requests
4
-
3
+ from automizor import session
5
4
  from automizor.exceptions import AutomizorError
6
5
  from automizor.utils import JSON, get_api_config, get_headers
7
6
 
@@ -79,13 +78,7 @@ class Action:
79
78
  AutomizorError: If there is an error executing the action.
80
79
  """
81
80
  url = f"https://{self.url}/api/v2/action/{name}/execute?workspace={workspace}"
82
- try:
83
- response = requests.put(url, headers=self.headers, data=payload, timeout=90)
84
- response.raise_for_status()
85
- return response.json()
86
- except requests.HTTPError as exc:
87
- raise AutomizorError.from_response(
88
- exc.response, "Failed to execute action"
89
- ) from exc
90
- except Exception as exc:
91
- raise AutomizorError(f"Failed to execute action: {exc}") from exc
81
+ response = session.put(url, headers=self.headers, data=payload, timeout=90)
82
+ if response.status_code >= 400:
83
+ raise AutomizorError.from_response(response, "Failed to execute action")
84
+ return response.json()
@@ -1,7 +1,6 @@
1
1
  from typing import Optional
2
2
 
3
- import requests
4
-
3
+ from automizor import session
5
4
  from automizor.exceptions import AutomizorError
6
5
  from automizor.utils import JSON, get_api_config, get_headers
7
6
 
@@ -76,27 +75,18 @@ class DataStore:
76
75
  else {}
77
76
  )
78
77
  url = f"https://{self.url}/api/v1/workflow/datastore/{name}/values/"
79
- try:
80
- response = requests.get(
81
- url, headers=self.headers, params=params, timeout=10
82
- )
83
- response.raise_for_status()
84
- return response.json()
85
- except requests.HTTPError as exc:
78
+ response = session.get(url, headers=self.headers, params=params, timeout=10)
79
+ if response.status_code >= 400:
86
80
  raise AutomizorError.from_response(
87
- exc.response, "Failed to get datastore values"
88
- ) from exc
89
- except Exception as exc:
90
- raise AutomizorError(f"Failed to get datastore values: {exc}") from exc
81
+ response, "Failed to get datastore values"
82
+ )
83
+
84
+ return response.json()
91
85
 
92
86
  def _set_values(self, name: str, values: JSON) -> None:
93
87
  url = f"https://{self.url}/api/v1/workflow/datastore/{name}/values/"
94
- try:
95
- response = requests.post(url, headers=self.headers, json=values, timeout=10)
96
- response.raise_for_status()
97
- except requests.HTTPError as exc:
88
+ response = session.post(url, headers=self.headers, json=values, timeout=10)
89
+ if response.status_code >= 400:
98
90
  raise AutomizorError.from_response(
99
- exc.response, "Failed to set datastore values"
100
- ) from exc
101
- except Exception as exc:
102
- raise AutomizorError(f"Failed to set datastore values: {exc}") from exc
91
+ response, "Failed to set datastore values"
92
+ )
@@ -0,0 +1,118 @@
1
+ from requests import Response
2
+
3
+
4
+ class AutomizorError(Exception):
5
+ def __init__(self, message: str, *, status_code=None, url=None):
6
+ self.status_code = status_code
7
+ self.url = url
8
+ super().__init__(message)
9
+
10
+ def __str__(self):
11
+ base = f"{self.args[0]}"
12
+ if self.status_code:
13
+ base += f" (status {self.status_code})"
14
+ if self.url:
15
+ base += f" → {self.url}"
16
+ return base
17
+
18
+ @classmethod
19
+ def from_response(cls, response: Response, message: str):
20
+ _STATUS_EXCEPTION_MAP = {
21
+ 400: InvalidRequest,
22
+ 401: Unauthorized,
23
+ 403: Forbidden,
24
+ 404: NotFound,
25
+ 429: RateLimitExceeded,
26
+ 500: InternalServerError,
27
+ 502: BadGateway,
28
+ 503: ServiceUnavailable,
29
+ 504: GatewayTimeout,
30
+ 520: OriginError,
31
+ 521: OriginDown,
32
+ 522: ConnectionTimedOut,
33
+ 523: OriginUnreachable,
34
+ 524: TimeoutOccurred,
35
+ 525: SSLHandshakeFailed,
36
+ 526: InvalidSSLCertificate,
37
+ 530: OriginDNSError,
38
+ }
39
+
40
+ exc_class = _STATUS_EXCEPTION_MAP.get(response.status_code, UnexpectedError)
41
+
42
+ return exc_class(
43
+ message,
44
+ status_code=response.status_code,
45
+ url=response.url,
46
+ )
47
+
48
+
49
+ class BadGateway(AutomizorError):
50
+ pass
51
+
52
+
53
+ class ConnectionTimedOut(AutomizorError):
54
+ pass
55
+
56
+
57
+ class Forbidden(AutomizorError):
58
+ pass
59
+
60
+
61
+ class GatewayTimeout(AutomizorError):
62
+ pass
63
+
64
+
65
+ class InternalServerError(AutomizorError):
66
+ pass
67
+
68
+
69
+ class InvalidRequest(AutomizorError):
70
+ pass
71
+
72
+
73
+ class InvalidSSLCertificate(AutomizorError):
74
+ pass
75
+
76
+
77
+ class NotFound(AutomizorError):
78
+ pass
79
+
80
+
81
+ class OriginDNSError(AutomizorError):
82
+ pass
83
+
84
+
85
+ class OriginDown(AutomizorError):
86
+ pass
87
+
88
+
89
+ class OriginError(AutomizorError):
90
+ pass
91
+
92
+
93
+ class OriginUnreachable(AutomizorError):
94
+ pass
95
+
96
+
97
+ class RateLimitExceeded(AutomizorError):
98
+ pass
99
+
100
+
101
+ class SSLHandshakeFailed(AutomizorError):
102
+ pass
103
+
104
+
105
+ class ServiceUnavailable(AutomizorError):
106
+ pass
107
+
108
+
109
+ class TimeoutOccurred(AutomizorError):
110
+ pass
111
+
112
+
113
+ class Unauthorized(AutomizorError):
114
+ pass
115
+
116
+
117
+ class UnexpectedError(AutomizorError):
118
+ pass
@@ -2,8 +2,7 @@ import json
2
2
  import os
3
3
  from typing import Optional
4
4
 
5
- import requests
6
-
5
+ from automizor import session
7
6
  from automizor.exceptions import AutomizorError
8
7
  from automizor.utils import JSON, get_api_config, get_headers
9
8
 
@@ -128,13 +127,7 @@ class Job:
128
127
 
129
128
  def _read_job_context(self) -> dict:
130
129
  url = f"https://{self.url}/api/v1/rpa/job/{self._job_id}/"
131
- try:
132
- response = requests.get(url, headers=self.headers, timeout=10)
133
- response.raise_for_status()
134
- return response.json().get("context", {})
135
- except requests.HTTPError as exc:
136
- raise AutomizorError.from_response(
137
- exc.response, "Failed to get job context"
138
- ) from exc
139
- except Exception as exc:
140
- raise AutomizorError(f"Failed to get job context: {exc}") from exc
130
+ response = session.get(url, headers=self.headers, timeout=10)
131
+ if response.status_code >= 400:
132
+ raise AutomizorError.from_response(response, "Failed to get job context")
133
+ return response.json().get("context", {})
@@ -1,7 +1,6 @@
1
1
  from typing import List, Optional
2
2
 
3
- import requests
4
-
3
+ from automizor import session
5
4
  from automizor.exceptions import AutomizorError, NotFound
6
5
  from automizor.utils import JSON, get_api_config, get_headers
7
6
 
@@ -77,21 +76,15 @@ class Storage:
77
76
  url = f"https://{self.url}/api/v1/storage/asset/"
78
77
  asset_names = []
79
78
 
80
- try:
81
- while url:
82
- response = requests.get(url, headers=self.headers, timeout=10)
83
- response.raise_for_status()
84
- data = response.json()
85
-
86
- for asset in data["results"]:
87
- asset_names.append(asset["name"])
88
- url = data["next"]
89
- except requests.HTTPError as exc:
90
- raise AutomizorError.from_response(
91
- exc.response, "Failed to list assets"
92
- ) from exc
93
- except Exception as exc:
94
- raise AutomizorError(f"Failed to list assets: {exc}") from exc
79
+ while url:
80
+ response = session.get(url, headers=self.headers, timeout=10)
81
+ if response.status_code >= 400:
82
+ raise AutomizorError.from_response(response, "Failed to list assets")
83
+ data = response.json()
84
+
85
+ for asset in data["results"]:
86
+ asset_names.append(asset["name"])
87
+ url = data["next"]
95
88
  return asset_names
96
89
 
97
90
  def delete_asset(self, name: str):
@@ -107,15 +100,9 @@ class Storage:
107
100
  """
108
101
 
109
102
  url = f"https://{self.url}/api/v1/storage/asset/{name}/"
110
- try:
111
- response = requests.delete(url, headers=self.headers, timeout=10)
112
- response.raise_for_status()
113
- except requests.HTTPError as exc:
114
- raise AutomizorError.from_response(
115
- exc.response, "Failed to delete asset"
116
- ) from exc
117
- except Exception as exc:
118
- raise AutomizorError(f"Failed to delete asset: {exc}") from exc
103
+ response = session.delete(url, headers=self.headers, timeout=10)
104
+ if response.status_code >= 400:
105
+ raise AutomizorError.from_response(response, "Failed to delete asset")
119
106
 
120
107
  def get_bytes(self, name: str) -> bytes:
121
108
  """
@@ -224,61 +211,39 @@ class Storage:
224
211
  """
225
212
 
226
213
  url = f"https://{self.url}/api/v1/storage/asset/"
227
- try:
228
- data = {
229
- "content_type": content_type,
230
- "name": name,
231
- }
232
- files = {"file": ("text.txt", content, content_type)}
233
- response = requests.post(
234
- url, headers=self.headers, files=files, data=data, timeout=10
235
- )
236
- response.raise_for_status()
237
- except requests.HTTPError as exc:
238
- raise AutomizorError.from_response(
239
- exc.response, "Failed to create asset"
240
- ) from exc
241
- except Exception as exc:
242
- raise AutomizorError(f"Failed to create asset: {exc}") from exc
214
+ data = {"content_type": content_type, "name": name}
215
+ files = {"file": ("text.txt", content, content_type)}
216
+ response = session.post(
217
+ url, headers=self.headers, files=files, data=data, timeout=10
218
+ )
219
+ if response.status_code >= 400:
220
+ raise AutomizorError.from_response(response, "Failed to create asset")
243
221
 
244
222
  def _download_file(self, name: str, mode: str = "content"):
245
223
  url = self._get_asset_url(name)
246
-
247
- try:
248
- response = requests.get(url=url, timeout=10)
249
- response.raise_for_status()
250
-
251
- match mode:
252
- case "content":
253
- return response.content
254
- case "json":
255
- return response.json()
256
- case "text":
257
- return response.text
258
- raise RuntimeError(f"Invalid mode {mode}")
259
- except requests.HTTPError as exc:
260
- raise AutomizorError.from_response(
261
- exc.response, "Failed to download asset"
262
- ) from exc
263
- except Exception as exc:
264
- raise AutomizorError(f"Failed to download asset: {exc}") from exc
224
+ response = session.get(url=url, timeout=10)
225
+ if response.status_code >= 400:
226
+ raise AutomizorError.from_response(response, "Failed to download asset")
227
+
228
+ match mode:
229
+ case "content":
230
+ return response.content
231
+ case "json":
232
+ return response.json()
233
+ case "text":
234
+ return response.text
235
+ raise RuntimeError(f"Invalid mode {mode}")
265
236
 
266
237
  def _get_asset_url(self, name: str) -> str:
267
238
  url = f"https://{self.url}/api/v1/storage/asset/{name}/"
268
- try:
269
- response = requests.get(url, headers=self.headers, timeout=10)
270
- response.raise_for_status()
271
-
272
- url = response.json().get("file")
273
- if url:
274
- return url
275
- raise RuntimeError("Url not found")
276
- except requests.HTTPError as exc:
277
- raise AutomizorError.from_response(
278
- exc.response, "Failed to get asset URL"
279
- ) from exc
280
- except Exception as exc:
281
- raise AutomizorError(f"Failed to get asset URL: {exc}") from exc
239
+ response = session.get(url, headers=self.headers, timeout=10)
240
+ if response.status_code >= 400:
241
+ raise AutomizorError.from_response(response, "Failed to get asset URL")
242
+
243
+ url = response.json().get("file")
244
+ if url:
245
+ return url
246
+ raise RuntimeError("Url not found")
282
247
 
283
248
  def _update_asset(self, name: str, content: bytes, content_type: str):
284
249
  """
@@ -295,19 +260,10 @@ class Storage:
295
260
  """
296
261
 
297
262
  url = f"https://{self.url}/api/v1/storage/asset/{name}/"
298
- try:
299
- data = {
300
- "content_type": content_type,
301
- "name": name,
302
- }
303
- files = {"file": ("text.txt", content, content_type)}
304
- response = requests.put(
305
- url, headers=self.headers, files=files, data=data, timeout=10
306
- )
307
- response.raise_for_status()
308
- except requests.HTTPError as exc:
309
- raise AutomizorError.from_response(
310
- exc.response, "Failed to update asset"
311
- ) from exc
312
- except Exception as exc:
313
- raise AutomizorError(f"Failed to update asset: {exc}") from exc
263
+ data = {"content_type": content_type, "name": name}
264
+ files = {"file": ("text.txt", content, content_type)}
265
+ response = session.put(
266
+ url, headers=self.headers, files=files, data=data, timeout=10
267
+ )
268
+ if response.status_code >= 400:
269
+ raise AutomizorError.from_response(response, "Failed to update asset")
@@ -1,8 +1,7 @@
1
1
  from dataclasses import asdict
2
2
  from typing import Optional
3
3
 
4
- import requests
5
-
4
+ from automizor import session
6
5
  from automizor.exceptions import AutomizorError, NotFound
7
6
  from automizor.utils import get_api_config, get_headers
8
7
 
@@ -113,43 +112,25 @@ class Vault:
113
112
 
114
113
  def _create_secret(self, secret: SecretContainer) -> SecretContainer:
115
114
  url = f"https://{self.url}/api/v1/vault/secret/"
116
- try:
117
- response = requests.post(
118
- url, headers=self.headers, timeout=10, json=asdict(secret)
119
- )
120
- response.raise_for_status()
121
- return SecretContainer(**response.json())
122
- except requests.HTTPError as exc:
123
- raise AutomizorError.from_response(
124
- exc.response, "Failed to create secret"
125
- ) from exc
126
- except Exception as exc:
127
- raise AutomizorError(f"Failed to create secret: {exc}") from exc
115
+ response = session.post(
116
+ url, headers=self.headers, timeout=10, json=asdict(secret)
117
+ )
118
+ if response.status_code >= 400:
119
+ raise AutomizorError.from_response(response, "Failed to create secret")
120
+ return SecretContainer(**response.json())
128
121
 
129
122
  def _get_secret(self, name: str) -> SecretContainer:
130
123
  url = f"https://{self.url}/api/v1/vault/secret/{name}/"
131
- try:
132
- response = requests.get(url, headers=self.headers, timeout=10)
133
- response.raise_for_status()
134
- return SecretContainer(**response.json())
135
- except requests.HTTPError as exc:
136
- raise AutomizorError.from_response(
137
- exc.response, "Failed to get secret"
138
- ) from exc
139
- except Exception as exc:
140
- raise AutomizorError(f"Failed to get secret: {exc}") from exc
124
+ response = session.get(url, headers=self.headers, timeout=10)
125
+ if response.status_code >= 400:
126
+ raise AutomizorError.from_response(response, "Failed to get secret")
127
+ return SecretContainer(**response.json())
141
128
 
142
129
  def _update_secret(self, secret: SecretContainer) -> SecretContainer:
143
130
  url = f"https://{self.url}/api/v1/vault/secret/{secret.name}/"
144
- try:
145
- response = requests.put(
146
- url, headers=self.headers, timeout=10, json=asdict(secret)
147
- )
148
- response.raise_for_status()
149
- return SecretContainer(**response.json())
150
- except requests.HTTPError as exc:
151
- raise AutomizorError.from_response(
152
- exc.response, "Failed to update secret"
153
- ) from exc
154
- except Exception as exc:
155
- raise AutomizorError(f"Failed to update secret: {exc}") from exc
131
+ response = session.put(
132
+ url, headers=self.headers, timeout=10, json=asdict(secret)
133
+ )
134
+ if response.status_code >= 400:
135
+ raise AutomizorError.from_response(response, "Failed to update secret")
136
+ return SecretContainer(**response.json())
@@ -1,7 +1,6 @@
1
1
  from typing import Optional
2
2
 
3
- import requests
4
-
3
+ from automizor import session
5
4
  from automizor.exceptions import AutomizorError
6
5
  from automizor.utils import get_api_config, get_headers
7
6
 
@@ -85,18 +84,13 @@ class Workflow:
85
84
  AutomizorError: If there is an error in creating the instance.
86
85
  """
87
86
  url = f"https://{self.url}/api/v1/workflow/instance/"
88
- try:
89
- data = {
90
- "business_key": business_key,
91
- "initial_data": payload,
92
- "process_model": process_model,
93
- "workspace": workspace,
94
- }
95
- response = requests.post(url, headers=self.headers, data=data, timeout=10)
96
- response.raise_for_status()
97
- except requests.HTTPError as exc:
98
- raise AutomizorError.from_response(
99
- exc.response, "Failed to create instance"
100
- ) from exc
101
- except Exception as exc:
102
- raise AutomizorError(f"Failed to create instance: {exc}") from exc
87
+
88
+ data = {
89
+ "business_key": business_key,
90
+ "initial_data": payload,
91
+ "process_model": process_model,
92
+ "workspace": workspace,
93
+ }
94
+ response = session.post(url, headers=self.headers, data=data, timeout=10)
95
+ if response.status_code >= 400:
96
+ raise AutomizorError.from_response(response, "Failed to create instance")
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: automizor
3
- Version: 0.4.15
3
+ Version: 0.4.17
4
4
  Summary: Python Automizor framework
5
5
  Home-page: https://github.com/automizor/automizor-python
6
6
  Author: Christian Fischer
@@ -16,3 +16,12 @@ Classifier: Programming Language :: Python :: 3.11
16
16
  Classifier: Programming Language :: Python :: 3.12
17
17
  License-File: LICENSE
18
18
  Requires-Dist: requests
19
+ Dynamic: author
20
+ Dynamic: author-email
21
+ Dynamic: classifier
22
+ Dynamic: home-page
23
+ Dynamic: keywords
24
+ Dynamic: license
25
+ Dynamic: license-file
26
+ Dynamic: requires-dist
27
+ Dynamic: summary
@@ -18,8 +18,6 @@ automizor/datastore/_container.py
18
18
  automizor/datastore/_datastore.py
19
19
  automizor/job/__init__.py
20
20
  automizor/job/_job.py
21
- automizor/log/__init__.py
22
- automizor/log/_log.py
23
21
  automizor/storage/__init__.py
24
22
  automizor/storage/_storage.py
25
23
  automizor/vault/__init__.py
@@ -1 +0,0 @@
1
- version = "0.4.15"
@@ -1,69 +0,0 @@
1
- from requests import Response
2
-
3
-
4
- class AutomizorError(Exception):
5
- def __init__(self, message, error=None):
6
- if error:
7
- message = f"{message}: {error}"
8
- super().__init__(message)
9
-
10
- def __str__(self):
11
- return f"{self.args[0]}"
12
-
13
- @classmethod
14
- def from_response(cls, response: Response, message: str):
15
- _STATUS_EXCEPTION_MAP = {
16
- 400: InvalidRequest,
17
- 401: Unauthorized,
18
- 403: Forbidden,
19
- 404: NotFound,
20
- 429: RateLimitExceeded,
21
- 500: InternalServerError,
22
- 502: BadGateway,
23
- 503: ServiceUnavailable,
24
- }
25
-
26
- try:
27
- error = dict(response.json()).get("detail", "Unknown error.")
28
- except Exception: # pylint: disable=broad-except
29
- error = response.text
30
-
31
- return _STATUS_EXCEPTION_MAP.get(response.status_code, UnexpectedError)(
32
- message, error
33
- )
34
-
35
-
36
- class BadGateway(AutomizorError):
37
- pass
38
-
39
-
40
- class Forbidden(AutomizorError):
41
- pass
42
-
43
-
44
- class InternalServerError(AutomizorError):
45
- pass
46
-
47
-
48
- class InvalidRequest(AutomizorError):
49
- pass
50
-
51
-
52
- class NotFound(AutomizorError):
53
- pass
54
-
55
-
56
- class RateLimitExceeded(AutomizorError):
57
- pass
58
-
59
-
60
- class ServiceUnavailable(AutomizorError):
61
- pass
62
-
63
-
64
- class Unauthorized(AutomizorError):
65
- pass
66
-
67
-
68
- class UnexpectedError(AutomizorError):
69
- pass
@@ -1,95 +0,0 @@
1
- from functools import lru_cache
2
-
3
- from ._log import VALUE
4
-
5
-
6
- @lru_cache
7
- def _get_log():
8
- from ._log import Log
9
-
10
- return Log()
11
-
12
-
13
- def debug(msg: VALUE):
14
- """
15
- Writes a debug log message with a level of "DEBUG".
16
-
17
- Parameters:
18
- msg (VALUE): The log message to write. This can be a boolean, string, integer, float
19
- or a JSON-serializable dictionary or list.
20
- """
21
-
22
- _get_log().write_log("DEBUG", msg)
23
-
24
-
25
- def info(msg: VALUE):
26
- """
27
- Writes an info log message with a level of "INFO".
28
-
29
- Parameters:
30
- msg (VALUE): The log message to write. This can be a boolean, string, integer, float
31
- or a JSON-serializable dictionary or list.
32
- """
33
-
34
- _get_log().write_log("INFO", msg)
35
-
36
-
37
- def warning(msg: VALUE):
38
- """
39
- Writes a warning log message with a level of "WARNING".
40
-
41
- Parameters:
42
- msg (VALUE): The log message to write. This can be a boolean, string, integer, float
43
- or a JSON-serializable dictionary or list.
44
- """
45
-
46
- _get_log().write_log("WARNING", msg)
47
-
48
-
49
- def error(msg: VALUE):
50
- """
51
- Writes an error log message with a level of "ERROR".
52
-
53
- Parameters:
54
- msg (VALUE): The log message to write. This can be a boolean, string, integer, float
55
- or a JSON-serializable dictionary or list.
56
- """
57
-
58
- _get_log().write_log("ERROR", msg)
59
-
60
-
61
- def critical(msg: VALUE):
62
- """
63
- Writes a critical log message with a level of "CRITICAL".
64
-
65
- Parameters:
66
- msg (VALUE): The log message to write. This can be a boolean, string, integer, float
67
- or a JSON-serializable dictionary or list.
68
- """
69
-
70
- _get_log().write_log("CRITICAL", msg)
71
-
72
-
73
- def set_level(level: str):
74
- """
75
- Set the log level for filtering log messages.
76
-
77
- Parameters:
78
- level (str): The log level to set. Valid log levels are "DEBUG", "INFO",
79
- "WARNING", "ERROR", and "CRITICAL".
80
-
81
- Raises:
82
- ValueError: If an invalid log level is provided.
83
- """
84
-
85
- _get_log().set_level(level)
86
-
87
-
88
- __all__ = [
89
- "debug",
90
- "info",
91
- "warning",
92
- "error",
93
- "critical",
94
- "set_level",
95
- ]
@@ -1,97 +0,0 @@
1
- import json
2
- import os
3
- from datetime import datetime, timezone
4
- from typing import Dict, List, Union
5
-
6
- LOG_LEVELS = {
7
- "DEBUG": 1,
8
- "INFO": 2,
9
- "WARNING": 3,
10
- "ERROR": 4,
11
- "CRITICAL": 5,
12
- }
13
-
14
- JSON = Union[str, int, float, bool, None, Dict[str, "JSON"], List["JSON"]]
15
- VALUE = Union[str, int, float, bool, JSON]
16
-
17
-
18
- class Log:
19
- """
20
- `Log` is a class that facilitates logging messages to a local file, which can be
21
- useful for debugging and monitoring purposes. It provides a simple interface for
22
- writing log messages with different levels, such as "info", "warning", "error", etc.
23
-
24
- The log messages are stored in a JSON file, which can be easily parsed and analyzed
25
- later. This class does not provide any log rotation or cleanup mechanisms, so it is
26
- recommended to manage log files manually or use external log management tools.
27
-
28
- Example usage:
29
-
30
- .. code-block:: python
31
-
32
- from automizor import log
33
-
34
- # Set log level to INFO
35
- log.set_level("INFO")
36
-
37
- # Write a log message
38
- log.info("This is an info message")
39
- """
40
-
41
- def __init__(self):
42
- self.level = "INFO"
43
-
44
- def set_level(self, level: str):
45
- """
46
- Set the log level for filtering log messages.
47
-
48
- Parameters:
49
- level (str): The log level to set. Valid log levels are "DEBUG", "INFO",
50
- "WARNING", "ERROR", and "CRITICAL".
51
-
52
- Raises:
53
- ValueError: If an invalid log level is provided.
54
- """
55
-
56
- if level not in LOG_LEVELS:
57
- raise ValueError(f"Invalid log level: {level}")
58
-
59
- self.level = level
60
-
61
- def write_log(self, level: str, msg: VALUE):
62
- """
63
- Write a log message with the specified log level.
64
-
65
- Parameters:
66
- level (str): The log level of the message. Valid log levels are "DEBUG", "INFO",
67
- "WARNING", "ERROR", and "CRITICAL".
68
- msg (VALUE): The log message to write. This can be a boolean, string, integer, float
69
- or a JSON-serializable dictionary or list.
70
-
71
- Raises:
72
- ValueError: If an invalid log level is provided.
73
- """
74
-
75
- if level not in LOG_LEVELS:
76
- raise ValueError(f"Invalid log level: {level}")
77
-
78
- if LOG_LEVELS[level] < LOG_LEVELS[self.level]:
79
- return
80
-
81
- data = []
82
- file_path = "output/log.json"
83
- try:
84
- if os.path.exists(file_path):
85
- with open(file_path, "r", encoding="utf-8") as file:
86
- data = json.load(file)
87
- except json.JSONDecodeError:
88
- pass
89
-
90
- if isinstance(msg, (dict, list)):
91
- msg = json.dumps(msg, ensure_ascii=False)
92
-
93
- timestamp = datetime.now(timezone.utc).isoformat()
94
- data.append({"level": level, "msg": msg, "timestamp": timestamp})
95
-
96
- with open(file_path, "w", encoding="utf-8") as file:
97
- json.dump(data, file, ensure_ascii=False)
File without changes
File without changes
File without changes
File without changes
File without changes