Debian Codegraph @

src/globus_sdk/services/gcs/response.py

raw
1 from __future__ import annotations
2
3 import re
4 import typing as t
5
6 from globus_sdk.response import GlobusHTTPResponse, IterableResponse
7
8
9 class IterableGCSResponse(IterableResponse):
10 """
11 Response class for non-paged list oriented resources. Allows top level
12 fields to be accessed normally via standard item access, and also
13 provides a convenient way to iterate over the sub-item list in the
14 ``data`` key:
15
16 >>> print("Path:", r["path"])
17 >>> # Equivalent to: for item in r["data"]
18 >>> for item in r:
19 >>> print(item["name"], item["type"])
20 """
21
22 default_iter_key = "data"
23
24
25 class UnpackingGCSResponse(GlobusHTTPResponse):
26 """
27 An "unpacking" response looks for a "data" array in the response data, which is
28 expected to have dict elements. The "data" is traversed until the first matching
29 object is found, and this is presented as the ``data`` property of the response.
30
31 The full response data is available as ``full_data``.
32
33 If the expected datatype is not found in the array, or the array is missing, the
34 ``data`` will be the full response data (identical to ``full_data``).
35
36 :param match: Either a string containing a DATA_TYPE prefix, or an arbitrary
37 callable which does the matching
38 """
39
40 def _default_unpacking_match(
41 self, spec: str
42 ) -> t.Callable[[dict[str, t.Any]], bool]:
43 if not re.fullmatch(r"\w+", spec):
44 raise ValueError("Invalid UnpackingGCSResponse specification.")
45
46 def match_func(data: dict[str, t.Any]) -> bool:
47 if not ("DATA_TYPE" in data and isinstance(data["DATA_TYPE"], str)):
48 return False
49 if "#" not in data["DATA_TYPE"]:
50 return False
51 name, _version = data["DATA_TYPE"].split("#", 1)
52 return name == spec
53
54 return match_func
55
56 def __init__(
57 self,
58 response: GlobusHTTPResponse,
59 match: str | t.Callable[[dict[str, t.Any]], bool],
60 ) -> None:
61 super().__init__(response)
62
63 if callable(match):
64 self._match_func = match
65 else:
66 self._match_func = self._default_unpacking_match(match)
67
68 self._unpacked_data: dict[str, t.Any] | None = None
69 self._did_unpack = False
70
71 @property
72 def full_data(self) -> t.Any:
73 """
74 The full, parsed JSON response data.
75 ``None`` if the data cannot be parsed as JSON.
76 """
77 return self._parsed_json
78
79 def _unpack(self) -> dict[str, t.Any] | None:
80 """
81 Unpack the response from the `"data"` array, returning the first match found.
82 If no matches are founds, or the data is the wrong shape, return None.
83 """
84 if isinstance(self._parsed_json, dict) and isinstance(
85 self._parsed_json.get("data"), list
86 ):
87 for item in self._parsed_json["data"]:
88 if isinstance(item, dict) and self._match_func(item):
89 return item
90 return None
91
92 @property
93 def data(self) -> t.Any:
94 # only do the unpacking operation once, as it may be expensive on large payloads
95 if not self._did_unpack:
96 self._unpacked_data = self._unpack()
97 self._did_unpack = True
98
99 if self._unpacked_data is not None:
100 return self._unpacked_data
101 return self._parsed_json