| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import collections.abc |
| 4 |
import json |
| 5 |
import logging |
| 6 |
import typing as t |
| 7 |
from functools import cached_property |
| 8 |
|
| 9 |
from globus_sdk._internal import guards |
| 10 |
|
| 11 |
log = logging.getLogger(__name__) |
| 12 |
|
| 13 |
if t.TYPE_CHECKING: |
| 14 |
from requests import Response |
| 15 |
|
| 16 |
import globus_sdk |
| 17 |
|
| 18 |
__all__ = ( |
| 19 |
"GlobusHTTPResponse", |
| 20 |
"IterableResponse", |
| 21 |
"ArrayResponse", |
| 22 |
) |
| 23 |
|
| 24 |
|
| 25 |
class GlobusHTTPResponse: |
| 26 |
""" |
| 27 |
Response object that wraps an HTTP response from the underlying HTTP |
| 28 |
library. If the response is JSON, the parsed data will be available in |
| 29 |
``data``, otherwise ``data`` will be ``None`` and ``text`` should |
| 30 |
be used instead. |
| 31 |
|
| 32 |
The most common response data is a JSON dictionary. To make |
| 33 |
handling this type of response as seamless as possible, the |
| 34 |
``GlobusHTTPResponse`` object implements the immutable mapping protocol for |
| 35 |
dict-style access. This is just an alias for access to the underlying data. |
| 36 |
|
| 37 |
If the response data is not a dictionary or list, item access will raise |
| 38 |
``TypeError``. |
| 39 |
|
| 40 |
>>> print("Response ID": r["id"]) # alias for r.data["id"] |
| 41 |
|
| 42 |
:ivar client: The client instance which made the request |
| 43 |
""" |
| 44 |
|
| 45 |
def __init__( |
| 46 |
self, |
| 47 |
response: Response | GlobusHTTPResponse, |
| 48 |
client: globus_sdk.BaseClient | None = None, |
| 49 |
) -> None: |
| 50 |
# init on a GlobusHTTPResponse: we are wrapping this data |
| 51 |
# the _response is None |
| 52 |
if isinstance(response, GlobusHTTPResponse): |
| 53 |
if client is not None: |
| 54 |
raise ValueError("Redundant client with wrapped response") |
| 55 |
self._wrapped: GlobusHTTPResponse | None = response |
| 56 |
self._response: Response | None = None |
| 57 |
self.client: globus_sdk.BaseClient = self._wrapped.client |
| 58 |
|
| 59 |
# init on a Response object, this is the "normal" case |
| 60 |
# _wrapped is None |
| 61 |
else: |
| 62 |
if client is None: |
| 63 |
raise ValueError("Missing client with normal response") |
| 64 |
self._wrapped = None |
| 65 |
self._response = response |
| 66 |
self.client = client |
| 67 |
|
| 68 |
@cached_property |
| 69 |
def _parsed_json(self) -> t.Any: |
| 70 |
# JSON decoding may raise a ValueError due to an invalid JSON |
| 71 |
# document. In the case of trying to fetch the "data" on an HTTP |
| 72 |
# response, this means we didn't get a JSON response. |
| 73 |
# store this as None, as in "no data" |
| 74 |
# |
| 75 |
# if the caller *really* wants the raw body of the response, they can |
| 76 |
# always use `text` |
| 77 |
if self._wrapped is not None: |
| 78 |
return self._wrapped._parsed_json |
| 79 |
|
| 80 |
if self._response is not None: |
| 81 |
try: |
| 82 |
return self._response.json() |
| 83 |
except ValueError: |
| 84 |
log.warning("response data did not parse as JSON, data=None") |
| 85 |
return None |
| 86 |
|
| 87 |
raise NotImplementedError( |
| 88 |
"Cannot read JSON data from a response which did not " |
| 89 |
"wrap another response or contain a transport-layer response." |
| 90 |
) |
| 91 |
|
| 92 |
@property |
| 93 |
def _raw_response(self) -> Response: |
| 94 |
# this is an internal property which traverses any series of wrapped responses |
| 95 |
# until reaching a requests response object |
| 96 |
if self._response is not None: |
| 97 |
return self._response |
| 98 |
elif self._wrapped is not None: |
| 99 |
return self._wrapped._raw_response |
| 100 |
else: # unreachable # pragma: no cover |
| 101 |
raise ValueError("could not find an inner response object") |
| 102 |
|
| 103 |
@property |
| 104 |
def http_status(self) -> int: |
| 105 |
"""The HTTP response status, as an integer.""" |
| 106 |
return self._raw_response.status_code |
| 107 |
|
| 108 |
@property |
| 109 |
def http_reason(self) -> str: |
| 110 |
""" |
| 111 |
The HTTP reason string from the response. |
| 112 |
|
| 113 |
This is the part of the status line after the status code, and typically is a |
| 114 |
string description of the status. If the status line is |
| 115 |
``HTTP/1.1 200 OK``, then this is the string ``"OK"``. |
| 116 |
""" |
| 117 |
return self._raw_response.reason |
| 118 |
|
| 119 |
@property |
| 120 |
def headers(self) -> t.Mapping[str, str]: |
| 121 |
""" |
| 122 |
The HTTP response headers as a case-insensitive mapping. |
| 123 |
|
| 124 |
For example, ``headers["Content-Length"]`` and ``headers["content-length"]`` are |
| 125 |
treated as equivalent. |
| 126 |
""" |
| 127 |
return self._raw_response.headers |
| 128 |
|
| 129 |
@property |
| 130 |
def content_type(self) -> str | None: |
| 131 |
return self.headers.get("Content-Type") |
| 132 |
|
| 133 |
@property |
| 134 |
def text(self) -> str: |
| 135 |
"""The raw response data as a string.""" |
| 136 |
return self._raw_response.text |
| 137 |
|
| 138 |
@property |
| 139 |
def binary_content(self) -> bytes: |
| 140 |
""" |
| 141 |
The raw response data in bytes. |
| 142 |
""" |
| 143 |
return self._raw_response.content |
| 144 |
|
| 145 |
@property |
| 146 |
def data(self) -> t.Any: |
| 147 |
return self._parsed_json |
| 148 |
|
| 149 |
def get(self, key: str, default: t.Any = None) -> t.Any: |
| 150 |
""" |
| 151 |
``get`` is just an alias for ``data.get(key, default)``, but with the added |
| 152 |
checks that if ``data`` is ``None`` or a list, it returns the default. |
| 153 |
|
| 154 |
:param key: The string key to lookup in the response if it is a dict |
| 155 |
:param default: The default value to be used if the data is null or a list |
| 156 |
""" |
| 157 |
if guards.is_optional(self.data, list): |
| 158 |
return default |
| 159 |
# NB: `default` is provided as a positional because the native dict type |
| 160 |
# doesn't recognize a keyword argument `default` |
| 161 |
return self.data.get(key, default) |
| 162 |
|
| 163 |
def __str__(self) -> str: |
| 164 |
"""The default __str__ for a response assumes that the data is valid |
| 165 |
JSON-dump-able.""" |
| 166 |
if self.data is not None: |
| 167 |
return json.dumps(self.data, indent=2, separators=(",", ": ")) |
| 168 |
return self.text |
| 169 |
|
| 170 |
def __repr__(self) -> str: |
| 171 |
return f"{self.__class__.__name__}({self.text})" |
| 172 |
|
| 173 |
def __getitem__(self, key: str | int | slice) -> t.Any: |
| 174 |
# force evaluation of the data property outside of the upcoming |
| 175 |
# try-catch so that we don't accidentally catch TypeErrors thrown |
| 176 |
# during the getter function itself |
| 177 |
data = self.data |
| 178 |
try: |
| 179 |
return data[key] |
| 180 |
except TypeError as err: |
| 181 |
log.error( |
| 182 |
f"Can't index into responses with underlying data of type {type(data)}" |
| 183 |
) |
| 184 |
# re-raise with an altered message and error type -- the issue is that |
| 185 |
# whatever data is in the response doesn't support indexing (e.g. a response |
| 186 |
# that is just an integer, parsed as json) |
| 187 |
# |
| 188 |
# "type" is ambiguous, but we don't know if it's the fault of the |
| 189 |
# class at large, or just a particular call's `data` property |
| 190 |
raise ValueError( |
| 191 |
"This type of response data does not support indexing." |
| 192 |
) from err |
| 193 |
|
| 194 |
def __contains__(self, item: t.Any) -> bool: |
| 195 |
""" |
| 196 |
``x in response`` is an alias for ``x in response.data`` |
| 197 |
""" |
| 198 |
if self.data is None: |
| 199 |
return False |
| 200 |
return item in self.data |
| 201 |
|
| 202 |
def __bool__(self) -> bool: |
| 203 |
""" |
| 204 |
``bool(response)`` is an alias for ``bool(response.data)`` |
| 205 |
""" |
| 206 |
return bool(self.data) |
| 207 |
|
| 208 |
|
| 209 |
class IterableResponse(GlobusHTTPResponse): |
| 210 |
"""This response class adds an __iter__ method on an 'iter_key' variable. |
| 211 |
The assumption is that iter produces dicts or dict-like mappings.""" |
| 212 |
|
| 213 |
default_iter_key: t.ClassVar[str] |
| 214 |
iter_key: str |
| 215 |
|
| 216 |
def __init__( |
| 217 |
self, |
| 218 |
response: Response | GlobusHTTPResponse, |
| 219 |
client: globus_sdk.BaseClient | None = None, |
| 220 |
*, |
| 221 |
iter_key: str | None = None, |
| 222 |
) -> None: |
| 223 |
if not hasattr(self, "default_iter_key"): |
| 224 |
raise TypeError( |
| 225 |
"Cannot instantiate an iterable response from a class " |
| 226 |
"which does not define a default iteration key." |
| 227 |
) |
| 228 |
iter_key = iter_key if iter_key is not None else self.default_iter_key |
| 229 |
self.iter_key = iter_key |
| 230 |
super().__init__(response, client) |
| 231 |
|
| 232 |
def __iter__(self) -> t.Iterator[t.Mapping[t.Any, t.Any]]: |
| 233 |
if not isinstance(self.data, dict): |
| 234 |
raise TypeError( |
| 235 |
"Cannot iterate on IterableResponse data when " |
| 236 |
f"type is '{type(self.data).__name__}'" |
| 237 |
) |
| 238 |
return iter(self.data[self.iter_key]) |
| 239 |
|
| 240 |
|
| 241 |
class ArrayResponse(GlobusHTTPResponse): |
| 242 |
"""This response class adds an ``__iter__`` method which assumes that the top-level |
| 243 |
data of the response is a JSON array.""" |
| 244 |
|
| 245 |
def __iter__(self) -> t.Iterator[t.Any]: |
| 246 |
if not isinstance(self.data, list): |
| 247 |
raise TypeError( |
| 248 |
"Cannot iterate on ArrayResponse data when " |
| 249 |
f"type is '{type(self.data).__name__}'" |
| 250 |
) |
| 251 |
return iter(self.data) |
| 252 |
|
| 253 |
def __len__(self) -> int: |
| 254 |
""" |
| 255 |
``len(response)`` is an alias for ``len(response.data)`` |
| 256 |
""" |
| 257 |
if not isinstance(self.data, collections.abc.Sequence): |
| 258 |
raise TypeError( |
| 259 |
"Cannot take len() on ArrayResponse data when " |
| 260 |
f"type is '{type(self.data).__name__}'" |
| 261 |
) |
| 262 |
return len(self.data) |
| 263 |
|
| 264 |
|
| 265 |
class IterableJSONAPIResponse(IterableResponse): |
| 266 |
"""This response class is for iterating on JSON:API responses that have an |
| 267 |
array of data in their top level `data` key.""" |
| 268 |
|
| 269 |
default_iter_key = "data" |