psytricks 2.3.0__tar.gz → 2.4.0a0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: psytricks
3
- Version: 2.3.0
3
+ Version: 2.4.0a0
4
4
  Summary: PowerShell Python Citrix Tricks.
5
5
  License-Expression: GPL-3.0-or-later
6
6
  License-File: LICENSE
@@ -14,6 +14,7 @@ Classifier: Programming Language :: Python :: 3.11
14
14
  Classifier: Programming Language :: Python :: 3.12
15
15
  Classifier: Programming Language :: Python :: 3.13
16
16
  Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Programming Language :: Python :: 3.15
17
18
  Requires-Dist: click (>=8.1.3,<9.0.0)
18
19
  Requires-Dist: loguru (>=0.7.0,<0.8.0)
19
20
  Requires-Dist: requests (>=2.30.0,<3.0.0)
@@ -6,7 +6,7 @@ authors = [
6
6
  ]
7
7
  license = "GPL-3.0-or-later"
8
8
  dynamic = ["readme"]
9
- version = "2.3.0"
9
+ version = "2.4.0-a.0"
10
10
 
11
11
  [tool.poetry]
12
12
  documentation = "https://imcf.one/apidocs/psytricks/psytricks.html"
@@ -3,7 +3,7 @@
3
3
  .. include:: ../../CHANGELOG.md
4
4
  """
5
5
 
6
- __version__ = "2.3.0"
6
+ __version__ = "2.4.0-a.0"
7
7
 
8
8
  # style exceptions for pdoc-include-only docstrings:
9
9
  # ruff: noqa: D400 (missing-trailing-period)
@@ -5,7 +5,7 @@ Collection of functions and other definitions to be sourced by other scripts.
5
5
  #>
6
6
 
7
7
  # the version variable will be filled by poetry at build time:
8
- $Version = "2.3.0"
8
+ $Version = "2.4.0-a.0"
9
9
 
10
10
 
11
11
  #region properties-selectors
@@ -0,0 +1,84 @@
1
+ """PSyTricks exception classes."""
2
+
3
+ import requests
4
+
5
+
6
+ class ResTricksConnectionError(requests.exceptions.ConnectionError, ConnectionError):
7
+ """Communicating with the ResTricks server failed.
8
+
9
+ Raised by `psytricks.wrapper.ResTricksWrapper` instead of the low-level
10
+ exceptions of `requests` / `urllib3` in case the server couldn't be reached
11
+ or didn't answer in time, using a concise message that states
12
+ the request method, the URL and the root cause of the failure (e.g.
13
+ `ConnectionRefusedError: [Errno 111] Connection refused`).
14
+
15
+ The class derives from both, `requests.exceptions.ConnectionError` and the
16
+ built-in `ConnectionError`, so existing code catching either of them will
17
+ continue to work.
18
+
19
+ The (potentially long) chain of underlying exceptions is suppressed when
20
+ raising this exception to keep tracebacks short, but the original exception
21
+ is still accessible through the `original` attribute (and `__context__`).
22
+
23
+ Parameters
24
+ ----------
25
+ message : str
26
+ The exception message.
27
+ method : str, optional
28
+ The HTTP method of the failed request (e.g. `GET`).
29
+ url : str, optional
30
+ The URL of the failed request.
31
+ original : Exception, optional
32
+ The exception that triggered this one.
33
+
34
+ Attributes
35
+ ----------
36
+ method : str or None
37
+ See the constructor for details.
38
+ url : str or None
39
+ See the constructor for details.
40
+ original : Exception or None
41
+ See the constructor for details.
42
+ reason : Exception or None
43
+ The innermost exception in the chain of `original`, i.e. the actual
44
+ root cause (e.g. a `ConnectionRefusedError` or `TimeoutError`).
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ message: str,
50
+ method: str | None = None,
51
+ url: str | None = None,
52
+ original: Exception | None = None,
53
+ ):
54
+ super().__init__(message)
55
+ self.method = method
56
+ self.url = url
57
+ self.original = original
58
+ self.reason = root_cause(original) if original is not None else None
59
+
60
+
61
+ def root_cause(ex: BaseException) -> BaseException:
62
+ """Find the innermost exception in the chain of the given one.
63
+
64
+ Follows `__cause__` (explicit chaining via `raise ... from ...`) and falls
65
+ back to `__context__` (implicit chaining, "during handling of the above
66
+ exception...") until the end of the chain is reached.
67
+
68
+ Parameters
69
+ ----------
70
+ ex : BaseException
71
+ The exception to start from.
72
+
73
+ Returns
74
+ -------
75
+ BaseException
76
+ The innermost exception of the chain (`ex` itself if it isn't chained).
77
+ """
78
+ seen = {id(ex)} # guard against (theoretically possible) cycles
79
+ while True:
80
+ nxt = ex.__cause__ or ex.__context__
81
+ if nxt is None or id(nxt) in seen:
82
+ return ex
83
+ seen.add(id(nxt))
84
+ ex = nxt
@@ -1,10 +1,9 @@
1
1
  """PowerShell Python Citrix Tricks."""
2
2
 
3
- import subprocess
4
3
  import json
5
4
  import os
5
+ import subprocess
6
6
  import time
7
-
8
7
  from os.path import dirname
9
8
  from pathlib import Path
10
9
  from sys import platform
@@ -14,7 +13,17 @@ from loguru import logger as log
14
13
 
15
14
  from . import __version__
16
15
  from .decoder import parse_powershell_json
17
- from .literals import Action, RequestName, MsgStyle
16
+ from .literals import Action, MsgStyle, RequestName
17
+ from .exceptions import ResTricksConnectionError, root_cause
18
+
19
+ # `requests` exceptions to be converted into a `ResTricksConnectionError`, i.e.
20
+ # the server couldn't be reached or didn't answer in time - other exceptions
21
+ # (e.g. `MissingSchema`, `InvalidHeader`) indicate a misconfiguration or a bug
22
+ # and are re-raised unchanged instead:
23
+ _CONNECTION_ERRORS = (
24
+ requests.exceptions.ConnectionError,
25
+ requests.exceptions.Timeout,
26
+ )
18
27
 
19
28
 
20
29
  class ResTricksWrapper:
@@ -135,10 +144,9 @@ class ResTricksWrapper:
135
144
 
136
145
  Raises
137
146
  ------
138
- ValueError
139
- Raised in case the server version doesn't match the local version.
140
- ConnectionError
141
- Raised in case the initial connection check failed.
147
+ ResTricksConnectionError
148
+ Raised in case the initial connection check failed (including a
149
+ mismatching server version), unless `verify` was set to `False`.
142
150
  """
143
151
  if self._connected:
144
152
  log.trace("Connection 🔌 established previously, not reconnecting.")
@@ -161,10 +169,16 @@ class ResTricksWrapper:
161
169
  self._connected = True
162
170
 
163
171
  except Exception as ex: # pylint: disable-msg=broad-except
164
- if self._verify:
165
- raise ConnectionError(
166
- f"Connecting to {self.base_url} failed: {ex}"
167
- ) from ex
172
+ if not self._verify:
173
+ return
174
+ # already a concise exception from send_get_request(), don't wrap it:
175
+ if isinstance(ex, ResTricksConnectionError):
176
+ raise
177
+ raise ResTricksConnectionError(
178
+ f"Connecting to {self.base_url} failed: {ex}",
179
+ url=self.base_url,
180
+ original=ex,
181
+ ) from ex
168
182
 
169
183
  def validate_version(self, server_ver) -> bool:
170
184
  """Validate the server version against the local module.
@@ -225,6 +239,32 @@ class ResTricksWrapper:
225
239
  log.error("Version mismatch! 🧨")
226
240
  return False
227
241
 
242
+ def _request_failed(
243
+ self, method: str, raw_url: str, ex: Exception
244
+ ) -> ResTricksConnectionError:
245
+ """Log a failed request and create a concise exception for it.
246
+
247
+ Parameters
248
+ ----------
249
+ method : str
250
+ The HTTP method of the failed request (e.g. `GET`).
251
+ raw_url : str
252
+ The part of the URL that was appended to `self.base_url`.
253
+ ex : Exception
254
+ The exception raised by `requests`, one of `_CONNECTION_ERRORS`.
255
+
256
+ Returns
257
+ -------
258
+ ResTricksConnectionError
259
+ The exception to be raised by the caller (using `from None` to
260
+ suppress the chain of low-level exceptions).
261
+ """
262
+ url = self.base_url + raw_url
263
+ reason = root_cause(ex)
264
+ msg = f"{method} request [{url}] failed: {type(reason).__name__}: {reason}"
265
+ log.error(msg)
266
+ return ResTricksConnectionError(msg, method=method, url=url, original=ex)
267
+
228
268
  def _check_response(self, response: requests.Response) -> None:
229
269
  """Check the HTTP response code and JSON status attributes."""
230
270
  self._write_response_dump(response)
@@ -300,9 +340,11 @@ class ResTricksWrapper:
300
340
  response = requests.get(
301
341
  self.base_url + raw_url, timeout=self.timeout, headers=self.headers
302
342
  )
343
+ except _CONNECTION_ERRORS as ex:
344
+ raise self._request_failed("GET", raw_url, ex) from None
303
345
  except Exception as ex: # pylint: disable-msg=broad-except
304
- log.error(f"GET request [{raw_url}] failed: {ex}")
305
- raise ex
346
+ log.error(f"GET request [{raw_url}] failed unexpectedly: {ex}")
347
+ raise
306
348
 
307
349
  try:
308
350
  data = response.json(object_hook=parse_powershell_json)
@@ -378,9 +420,11 @@ class ResTricksWrapper:
378
420
  timeout=self.timeout,
379
421
  headers=self.headers,
380
422
  )
423
+ except _CONNECTION_ERRORS as ex:
424
+ raise self._request_failed("POST", raw_url, ex) from None
381
425
  except Exception as ex: # pylint: disable-msg=broad-except
382
- log.error(f"POST request [{raw_url}] failed: {ex}")
383
- raise ex
426
+ log.error(f"POST request [{raw_url}] failed unexpectedly: {ex}")
427
+ raise
384
428
 
385
429
  self._check_response(response)
386
430
 
File without changes
File without changes
File without changes