automizor 0.3.0__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.
automizor/__init__.py CHANGED
@@ -1 +1 @@
1
- version = "0.3.0"
1
+ version = "0.4.0"
@@ -0,0 +1,69 @@
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
automizor/job/__init__.py CHANGED
@@ -1,6 +1,5 @@
1
1
  from functools import lru_cache
2
2
 
3
- from ._exceptions import AutomizorJobError
4
3
  from ._job import JSON
5
4
 
6
5
 
@@ -44,7 +43,6 @@ def set_result(name: str, value: JSON):
44
43
 
45
44
 
46
45
  __all__ = [
47
- "AutomizorJobError",
48
46
  "get_context",
49
47
  "set_result",
50
48
  ]
automizor/job/_job.py CHANGED
@@ -4,7 +4,8 @@ from typing import Dict, List, Union
4
4
 
5
5
  import requests
6
6
 
7
- from ._exceptions import AutomizorJobError
7
+ from automizor.exceptions import AutomizorError
8
+ from automizor.utils import get_api_config, get_headers
8
9
 
9
10
  JSON = Union[str, int, float, bool, None, Dict[str, "JSON"], List["JSON"]]
10
11
 
@@ -30,8 +31,7 @@ class Job:
30
31
  To use this class effectively, ensure that the following environment variables are
31
32
  set in your environment:
32
33
 
33
- - ``AUTOMIZOR_API_HOST``: The URL of the `Automizor API` host.
34
- - ``AUTOMIZOR_API_TOKEN``: The authentication token for API access.
34
+ - ``AUTOMIZOR_AGENT_TOKEN``: The token for authenticating against the `Automizor API`.
35
35
  - ``AUTOMIZOR_CONTEXT_FILE``: The path to a local file containing job context, if used.
36
36
  - ``AUTOMIZOR_JOB_ID``: The identifier for the current job, used when fetching context via API.
37
37
 
@@ -50,18 +50,12 @@ class Job:
50
50
  """
51
51
 
52
52
  def __init__(self):
53
- self._api_host = os.getenv("AUTOMIZOR_API_HOST")
54
- self._api_token = os.getenv("AUTOMIZOR_API_TOKEN")
55
- self._context_file = os.getenv("AUTOMIZOR_CONTEXT_FILE")
56
- self._job_id = os.getenv("AUTOMIZOR_JOB_ID")
53
+ self._context_file = os.getenv("AUTOMIZOR_CONTEXT_FILE", None)
54
+ self._job_id = os.getenv("AUTOMIZOR_JOB_ID", None)
57
55
 
56
+ self.url, self.token = get_api_config()
58
57
  self.session = requests.Session()
59
- self.session.headers.update(
60
- {
61
- "Authorization": f"Token {self._api_token}",
62
- "Content-Type": "application/json",
63
- }
64
- )
58
+ self.session.headers.update(get_headers(self.token))
65
59
 
66
60
  def get_context(self) -> dict:
67
61
  """
@@ -73,8 +67,7 @@ class Job:
73
67
  This is useful in environments where direct access to the `Automizor API` is
74
68
  not possible or preferred.
75
69
  2. The `Automizor API`, using the job ID (`AUTOMIZOR_JOB_ID`) to fetch the specific
76
- job context. This requires valid API host (`AUTOMIZOR_API_HOST`) and token
77
- (`AUTOMIZOR_API_TOKEN`) settings.
70
+ job context.
78
71
 
79
72
  Returns:
80
73
  A dictionary containing the job context.
@@ -125,10 +118,14 @@ class Job:
125
118
  return json.load(file)
126
119
 
127
120
  def _read_job_context(self) -> dict:
128
- url = f"https://{self._api_host}/api/v1/rpa/job/{self._job_id}/"
121
+ url = f"https://{self.url}/api/v1/rpa/job/{self._job_id}/"
129
122
  try:
130
123
  response = self.session.get(url, timeout=10)
131
124
  response.raise_for_status()
132
125
  return response.json().get("context", {})
126
+ except requests.HTTPError as exc:
127
+ raise AutomizorError.from_response(
128
+ exc.response, "Failed to get job context"
129
+ ) from exc
133
130
  except Exception as exc:
134
- raise AutomizorJobError(f"Failed to get job context: {exc}") from exc
131
+ raise AutomizorError("Failed to get job context") from exc
@@ -1,6 +1,8 @@
1
+ import json
2
+ import mimetypes
1
3
  from functools import lru_cache
4
+ from pathlib import Path
2
5
 
3
- from ._exceptions import AutomizorStorageError
4
6
  from ._storage import JSON
5
7
 
6
8
 
@@ -11,6 +13,30 @@ def _get_storage():
11
13
  return Storage()
12
14
 
13
15
 
16
+ def list_assets() -> list[str]:
17
+ """
18
+ Retrieves a list of all asset names.
19
+
20
+ Returns:
21
+ A list of all asset names.
22
+ """
23
+
24
+ storage = _get_storage()
25
+ return storage.list_assets()
26
+
27
+
28
+ def delete_asset(name: str) -> None:
29
+ """
30
+ Deletes the specified asset.
31
+
32
+ Parameters:
33
+ name: The name identifier of the asset to delete.
34
+ """
35
+
36
+ storage = _get_storage()
37
+ storage.delete_asset(name)
38
+
39
+
14
40
  def get_bytes(name: str) -> bytes:
15
41
  """
16
42
  Retrieves the specified asset as raw bytes.
@@ -72,10 +98,82 @@ def get_text(name: str) -> str:
72
98
  return storage.get_text(name)
73
99
 
74
100
 
101
+ def set_bytes(name: str, data: bytes, content_type="application/octet-stream") -> None:
102
+ """
103
+ Uploads raw bytes as an asset.
104
+
105
+ Parameters:
106
+ name: The name identifier of the asset to upload.
107
+ data: The raw byte content to upload.
108
+ content_type: The MIME type of the asset.
109
+ """
110
+
111
+ storage = _get_storage()
112
+ storage.set_bytes(name, data, content_type)
113
+
114
+
115
+ def set_file(name: str, path: str, content_type: str = None) -> None:
116
+ """
117
+ Uploads a file as an asset.
118
+
119
+ Parameters:
120
+ name: The name identifier of the asset to upload.
121
+ path: The filesystem path of the file to upload.
122
+ content_type: The MIME type of the asset.
123
+ """
124
+
125
+ content = Path(path).read_bytes()
126
+ if content_type is None:
127
+ content_type, _ = mimetypes.guess_type(path)
128
+ if content_type is None:
129
+ content_type = "application/octet-stream"
130
+
131
+ storage = _get_storage()
132
+ storage.set_bytes(name, content, content_type)
133
+
134
+
135
+ def set_json(name: str, value: JSON, **kwargs) -> None:
136
+ """
137
+ Uploads JSON data as an asset.
138
+
139
+ Parameters:
140
+ name: The name identifier of the asset to upload.
141
+ value: The JSON data to upload.
142
+ kwargs: Additional keyword arguments to pass to json.dumps.
143
+ """
144
+
145
+ content = json.dumps(value, **kwargs).encode("utf-8")
146
+ content_type = "application/json"
147
+
148
+ storage = _get_storage()
149
+ storage.set_bytes(name, content, content_type)
150
+
151
+
152
+ def set_text(name: str, text: str) -> None:
153
+ """
154
+ Uploads text content as an asset.
155
+
156
+ Parameters:
157
+ name: The name identifier of the asset to upload.
158
+ text: The text content to upload.
159
+ """
160
+
161
+ content = text.encode("utf-8")
162
+ content_type = "text/plain"
163
+
164
+ storage = _get_storage()
165
+ storage.set_bytes(name, content, content_type)
166
+
167
+
75
168
  __all__ = [
76
- "AutomizorStorageError",
169
+ "list_assets",
170
+ "delete_asset",
77
171
  "get_bytes",
78
172
  "get_file",
79
173
  "get_json",
80
174
  "get_text",
175
+ "set_bytes",
176
+ "set_file",
177
+ "set_json",
178
+ "set_text",
81
179
  ]
@@ -1,9 +1,9 @@
1
- import os
2
1
  from typing import Dict, List, Union
3
2
 
4
3
  import requests
5
4
 
6
- from ._exceptions import AutomizorStorageError
5
+ from automizor.exceptions import AutomizorError, NotFound
6
+ from automizor.utils import get_api_config, get_headers
7
7
 
8
8
  JSON = Union[str, int, float, bool, None, Dict[str, "JSON"], List["JSON"]]
9
9
 
@@ -23,8 +23,7 @@ class Storage:
23
23
  To use this class effectively, ensure that the following environment variables are
24
24
  set in your environment:
25
25
 
26
- - ``AUTOMIZOR_API_HOST``: Specifies the host URL of the `Automizor Storage API`.
27
- - ``AUTOMIZOR_API_TOKEN``: Provides the token required for API authentication.
26
+ - ``AUTOMIZOR_AGENT_TOKEN``: The token for authenticating against the `Automizor API`.
28
27
 
29
28
  Example usage:
30
29
 
@@ -32,30 +31,82 @@ class Storage:
32
31
 
33
32
  from automizor import storage
34
33
 
35
- # To get bytes of an asset
36
- bytes_data = storage.get_bytes("asset_name")
34
+ # To list all assets
35
+ asset_names = storage.list_assets()
37
36
 
38
- # To save an asset to a file
39
- file_path = storage.get_file("asset_name", "/path/to/save/file")
37
+ # To delete an asset
38
+ storage.delete_asset("AssetName")
40
39
 
41
- # To retrieve an asset as JSON
42
- json_data = storage.get_json("asset_name")
40
+ # Save an asset
41
+ storage.set_bytes("AssetName", b"Hello, World!")
42
+ storage.set_file("AssetName", "/path/to/file")
43
+ storage.set_json("AssetName", {"key": "value"})
44
+ storage.set_text("AssetName", "Hello, World!")
43
45
 
44
- # To get the text content of an asset
45
- text_data = storage.get_text("asset_name")
46
+ # Get an asset
47
+ bytes_data = storage.get_bytes("AssetName")
48
+ file_path = storage.get_file("AssetName", "/path/to/save/file")
49
+ json_data = storage.get_json("AssetName")
50
+ text_data = storage.get_text("AssetName")
46
51
  """
47
52
 
48
53
  def __init__(self):
49
- self._api_host = os.getenv("AUTOMIZOR_API_HOST")
50
- self._api_token = os.getenv("AUTOMIZOR_API_TOKEN")
51
-
54
+ self.url, self.token = get_api_config()
52
55
  self.session = requests.Session()
53
- self.session.headers.update(
54
- {
55
- "Authorization": f"Token {self._api_token}",
56
- "Content-Type": "application/json",
57
- }
58
- )
56
+ self.session.headers.update(get_headers(self.token))
57
+
58
+ def list_assets(self) -> List[str]:
59
+ """
60
+ Retrieves a list of all asset names.
61
+
62
+ This function fetches the names of all assets stored in the storage service,
63
+ providing a convenient way to list and identify the available assets.
64
+
65
+ Returns:
66
+ A list of all asset names.
67
+ """
68
+ url = f"https://{self.url}/api/v1/storage/asset/"
69
+ asset_names = []
70
+
71
+ try:
72
+ while url:
73
+ response = self.session.get(url, timeout=10)
74
+ response.raise_for_status()
75
+ data = response.json()
76
+
77
+ for asset in data["results"]:
78
+ asset_names.append(asset["name"])
79
+ url = data["next"]
80
+ except requests.HTTPError as exc:
81
+ raise AutomizorError.from_response(
82
+ exc.response, "Failed to list assets"
83
+ ) from exc
84
+ except Exception as exc:
85
+ raise AutomizorError("Failed to list assets") from exc
86
+ return asset_names
87
+
88
+ def delete_asset(self, name: str) -> None:
89
+ """
90
+ Deletes the specified asset.
91
+
92
+ This function deletes the asset identified by `name` from the storage service.
93
+ It is useful for removing assets that are no longer needed or should be cleaned
94
+ up to free up storage space.
95
+
96
+ Parameters:
97
+ name: The name identifier of the asset to delete.
98
+ """
99
+
100
+ url = f"https://{self.url}/api/v1/storage/asset/{name}/"
101
+ try:
102
+ response = self.session.delete(url, timeout=10)
103
+ response.raise_for_status()
104
+ except requests.HTTPError as exc:
105
+ raise AutomizorError.from_response(
106
+ exc.response, "Failed to delete asset"
107
+ ) from exc
108
+ except Exception as exc:
109
+ raise AutomizorError("Failed to delete asset") from exc
59
110
 
60
111
  def get_bytes(self, name: str) -> bytes:
61
112
  """
@@ -72,8 +123,7 @@ class Storage:
72
123
  The raw byte content of the asset.
73
124
  """
74
125
 
75
- url = self._get_asset_url(name)
76
- return self._download_file(url, mode="content")
126
+ return self._download_file(name, mode="content")
77
127
 
78
128
  def get_file(self, name: str, path: str) -> str:
79
129
  """
@@ -92,8 +142,7 @@ class Storage:
92
142
  The path to the saved file, confirming the operation's success.
93
143
  """
94
144
 
95
- url = self._get_asset_url(name)
96
- content = self._download_file(url, mode="content")
145
+ content = self._download_file(name, mode="content")
97
146
  with open(path, "wb") as file:
98
147
  file.write(content)
99
148
  return path
@@ -113,8 +162,7 @@ class Storage:
113
162
  The parsed JSON data, which can be a dict, list, or primitive data type.
114
163
  """
115
164
 
116
- url = self._get_asset_url(name)
117
- return self._download_file(url, mode="json")
165
+ return self._download_file(name, mode="json")
118
166
 
119
167
  def get_text(self, name: str) -> str:
120
168
  """
@@ -131,13 +179,62 @@ class Storage:
131
179
  The content of the asset as a text string.
132
180
  """
133
181
 
182
+ return self._download_file(name, mode="text")
183
+
184
+ def set_bytes(self, name: str, content: bytes, content_type: str) -> None:
185
+ """
186
+ Uploads the specified content as a new asset.
187
+
188
+ This function uploads the provided `content` as a new asset with the specified
189
+ `name`. It is useful for creating new assets or updating existing ones with
190
+ fresh content.
191
+
192
+ Parameters:
193
+ name: The name identifier of the asset to create.
194
+ content: The raw byte content of the asset.
195
+ content_type: The MIME type of the asset content.
196
+ """
197
+
198
+ try:
199
+ self._update_asset(name, content, content_type)
200
+ except NotFound:
201
+ self._create_asset(name, content, content_type)
202
+
203
+ def _create_asset(self, name: str, content: bytes, content_type: str) -> None:
204
+ """
205
+ Creates a new asset with the specified content.
206
+
207
+ This function creates a new asset with the specified `name` and `content` in the
208
+ storage service. It is useful for uploading new assets or updating existing ones
209
+ with fresh content.
210
+
211
+ Parameters:
212
+ name: The name identifier of the asset to create.
213
+ content: The raw byte content of the asset.
214
+ content_type: The MIME type of the asset content.
215
+ """
216
+
217
+ url = f"https://{self.url}/api/v1/storage/asset/"
218
+ try:
219
+ data = {
220
+ "content_type": content_type,
221
+ "name": name,
222
+ }
223
+ files = {"file": ("text.txt", content, content_type)}
224
+ response = self.session.post(url, files=files, data=data, timeout=10)
225
+ response.raise_for_status()
226
+ except requests.HTTPError as exc:
227
+ raise AutomizorError.from_response(
228
+ exc.response, "Failed to create asset"
229
+ ) from exc
230
+ except Exception as exc:
231
+ raise AutomizorError("Failed to create asset") from exc
232
+
233
+ def _download_file(self, name: str, mode: str = "content"):
134
234
  url = self._get_asset_url(name)
135
- return self._download_file(url, mode="text")
136
235
 
137
- def _download_file(self, url: str, mode: str = "content"):
138
236
  try:
139
- session = requests.Session()
140
- response = session.get(url, timeout=10)
237
+ response = requests.get(url=url, timeout=10)
141
238
  response.raise_for_status()
142
239
 
143
240
  match mode:
@@ -148,11 +245,15 @@ class Storage:
148
245
  case "text":
149
246
  return response.text
150
247
  raise RuntimeError(f"Invalid mode {mode}")
248
+ except requests.HTTPError as exc:
249
+ raise AutomizorError.from_response(
250
+ exc.response, "Failed to download asset"
251
+ ) from exc
151
252
  except Exception as exc:
152
- raise AutomizorStorageError(f"Failed to download asset: {exc}") from exc
253
+ raise AutomizorError("Failed to download asset") from exc
153
254
 
154
255
  def _get_asset_url(self, name: str) -> str:
155
- url = f"https://{self._api_host}/api/v1/storage/asset/{name}/"
256
+ url = f"https://{self.url}/api/v1/storage/asset/{name}/"
156
257
  try:
157
258
  response = self.session.get(url, timeout=10)
158
259
  response.raise_for_status()
@@ -161,5 +262,39 @@ class Storage:
161
262
  if url:
162
263
  return url
163
264
  raise RuntimeError("Url not found")
265
+ except requests.HTTPError as exc:
266
+ raise AutomizorError.from_response(
267
+ exc.response, "Failed to get asset URL"
268
+ ) from exc
269
+ except Exception as exc:
270
+ raise AutomizorError("Failed to get asset URL") from exc
271
+
272
+ def _update_asset(self, name: str, content: bytes, content_type: str) -> None:
273
+ """
274
+ Updates the specified asset with new content.
275
+
276
+ This function updates the asset identified by `name` with fresh content
277
+ provided as `content`. It is useful for modifying existing assets without
278
+ creating a new asset, ensuring that the asset's content is up-to-date.
279
+
280
+ Parameters:
281
+ name: The name identifier of the asset to update.
282
+ content: The raw byte content of the asset.
283
+ content_type: The MIME type of the asset content.
284
+ """
285
+
286
+ url = f"https://{self.url}/api/v1/storage/asset/{name}/"
287
+ try:
288
+ data = {
289
+ "content_type": content_type,
290
+ "name": name,
291
+ }
292
+ files = {"file": ("text.txt", content, content_type)}
293
+ response = self.session.put(url, files=files, data=data, timeout=10)
294
+ response.raise_for_status()
295
+ except requests.HTTPError as exc:
296
+ raise AutomizorError.from_response(
297
+ exc.response, "Failed to update asset"
298
+ ) from exc
164
299
  except Exception as exc:
165
- raise AutomizorStorageError(f"Failed to get asset url: {exc}") from exc
300
+ raise AutomizorError("Failed to update asset") from exc
@@ -0,0 +1,31 @@
1
+ import os
2
+ import platform
3
+
4
+ from automizor import version
5
+ from automizor.exceptions import AutomizorError
6
+
7
+ OS_SYSTEM, OS_RELEASE, _ = platform.system_alias(
8
+ platform.system(), platform.release(), platform.version()
9
+ )
10
+
11
+
12
+ def get_api_config() -> tuple[str, str]:
13
+ token_string = os.getenv("AUTOMIZOR_AGENT_TOKEN")
14
+
15
+ if not token_string:
16
+ raise AutomizorError("AUTOMIZOR_AGENT_TOKEN is not set.")
17
+
18
+ try:
19
+ token, url = token_string.strip().split("@")
20
+ except ValueError as exc:
21
+ raise AutomizorError(
22
+ "AUTOMIZOR_AGENT_TOKEN is not in the correct format."
23
+ ) from exc
24
+ return url, token
25
+
26
+
27
+ def get_headers(token: str) -> dict:
28
+ return {
29
+ "Authorization": f"Token {token}",
30
+ "User-Agent": f"Automizor/{version} {OS_SYSTEM}/{OS_RELEASE}",
31
+ }
@@ -1,7 +1,7 @@
1
1
  from functools import lru_cache
2
+ from typing import Any, Dict
2
3
 
3
- from ._exceptions import AutomizorVaultError
4
- from ._secret import Secret
4
+ from ._container import SecretContainer
5
5
 
6
6
 
7
7
  @lru_cache
@@ -11,10 +11,40 @@ def _get_vault():
11
11
  return Vault()
12
12
 
13
13
 
14
- def get_secret(name: str) -> Secret:
14
+ def create_secret(
15
+ name: str,
16
+ value: Dict[str, Any],
17
+ description: str = "",
18
+ ) -> SecretContainer:
15
19
  """
16
- Retrieves a secret by its name. Fetches from a local file or queries the
17
- `Automizor API`, based on configuration.
20
+ Creates a new secret. Stores the secret in the `Automizor API`.
21
+ If the secret already exists, it will be updated.
22
+
23
+ Args:
24
+ name: The name of the secret.
25
+ value: The value of the secret.
26
+ description: The description of the secret.
27
+
28
+ Returns:
29
+ The created secret.
30
+
31
+ Raises:
32
+ AutomizorVaultError: If creating the secret fails.
33
+ """
34
+
35
+ secret = SecretContainer(
36
+ name=name,
37
+ description=description,
38
+ value=value,
39
+ )
40
+
41
+ vault = _get_vault()
42
+ return vault.create_secret(secret)
43
+
44
+
45
+ def get_secret(name: str) -> SecretContainer:
46
+ """
47
+ Retrieves a secret by its name. Fetches from the `Automizor API`.
18
48
 
19
49
  Args:
20
50
  name: The name of the secret to retrieve.
@@ -30,10 +60,9 @@ def get_secret(name: str) -> Secret:
30
60
  return vault.get_secret(name)
31
61
 
32
62
 
33
- def set_secret(secret: Secret) -> Secret:
63
+ def set_secret(secret: SecretContainer) -> SecretContainer:
34
64
  """
35
- Updates an existing secret. Updates to a local file or to the
36
- `Automizor API`, based on configuration.
65
+ Updates an existing secret. Updates to the `Automizor API`.
37
66
 
38
67
  Args:
39
68
  secret: The secret to update.
@@ -50,8 +79,8 @@ def set_secret(secret: Secret) -> Secret:
50
79
 
51
80
 
52
81
  __all__ = [
53
- "AutomizorVaultError",
54
- "Secret",
82
+ "SecretContainer",
83
+ "create_secret",
55
84
  "get_secret",
56
85
  "set_secret",
57
86
  ]