18 from typing
import Union, Type, TypeVar, Optional, Iterator, Any
19 from http
import HTTPStatus
21 from requests
import Response
22 from requests.structures
import CaseInsensitiveDict
24 from .request_type
import RequestType
27 JsonType = TypeVar(
"JsonType", bound = Union[list, dict])
33 Represents Coretex backend response to network request
38 python.requests HTTP reponse
40 endpoint to which the request was sent
43 def __init__(self, response: Response, endpoint: str):
44 self.
_raw_raw = response
48 def statusCode(self) -> int:
50 Status code of the HTTP response
53 return self.
_raw_raw.status_code
61 return self.
_raw_raw.headers
65 Checks if request has failed
69 bool -> True if request has failed, False if request has not failed
72 return not self.
_raw_raw.ok
76 Checks if request was unauthorized
80 bool -> True if status code is 401 and request has failed, False if not
88 bool -> True if the request method which created this reponse is HEAD, False if not
91 return self.
_raw_raw.request.method == RequestType.head.value
93 def getJson(self, type_: Type[JsonType]) -> JsonType:
95 Converts HTTP response body to json
100 list or dict types to which the json should be cast
104 JsonType -> Either a list or a dict object depending on type_ parameter
108 ValueError -> If "Content-Type" header was not "application/json"
109 TypeError -> If it was not possible to convert body to type of passed "type_" parameter
112 if not "application/json" in self.
headersheaders.get(
"Content-Type",
""):
113 raise ValueError(f
">> [Coretex] Trying to convert request response to json but response \"Content-Type\" was \"{self.headers.get('Content-Type')}\"")
115 value = self.
_raw_raw.json()
116 if not isinstance(value, type_):
117 raise TypeError(f
">> [Coretex] Expected json response to be of type \"{type_.__name__}\", received \"{type(value).__name__}\"")
125 bytes -> body of the request as bytes
128 return self.
_raw_raw.content
130 def stream(self, chunkSize: Optional[int] = 1, decodeUnicode: bool =
False) -> Iterator[Any]:
132 Downloads HTTP response in chunks and returns them as they are being downloaded
136 chunkSize : Optional[int]
137 A value of None will function differently depending on the value of stream.
138 stream = True will read data as it arrives in whatever size the chunks are
139 received. If stream = False, data is returned as a single chunk.
141 If decode_unicode is True, content will be decoded using the best
142 available encoding based on the response
146 Iterator[Any] -> HTTP response as chunks
149 return self.
_raw_raw.iter_content(chunkSize, decodeUnicode)
155 Exception which is raised when an request fails.
156 Request is marked as failed when the http code is: >= 400
159 def __init__(self, response: NetworkResponse, message: str) ->
None:
160 if not response.hasFailed():
161 raise ValueError(
">> [Coretex] Invalid request response")
166 responseJson = response.getJson(dict)
168 if "message" in responseJson:
169 responseMessage = responseJson[
"message"]
171 responseMessage = response._raw.content.decode()
173 responseMessage = response._raw.content.decode()
175 super().__init__(f
">> [Coretex] {message}. Reason: {responseMessage}")
JsonType getJson(self, Type[JsonType] type_)
bool isUnauthorized(self)
CaseInsensitiveDict headers(self)
Iterator[Any] stream(self, Optional[int] chunkSize=1, bool decodeUnicode=False)