models.py
This file
Path
httpcore/models.py
654 lines · 20.4 KiB · Python
Last changed by
Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
History of this fileTake it
Add response.text and response.encodingTom Christiebefore adoptiond8df61b
line 1why, one step back1import cgiMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 2–3why, one step back2import typing3Add response.text and response.encodingTom Christiebefore adoptiond8df61b
line 4why, one step back4import chardetAdd idna support. More tests.Tom Christiebefore adoptionb948798
line 5why, one step back5import idnaUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 6why, one step back6import rfc3986Add response.text and response.encodingTom Christiebefore adoptiond8df61b
line 7why, one step back7Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 8why, one step back8from .config import SSLConfig, TimeoutConfigReorganise structureTom Christiebefore adoption0c6f618
line 9why, one step back9from .constants import codesMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 10–16why, one step back10from .decoders import (11 ACCEPT_ENCODING,12 SUPPORTED_DECODERS,13 Decoder,14 IdentityDecoder,15 MultiDecoder,16)Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 17–23why, one step back17from .exceptions import (18 HttpError,19 InvalidURL,20 ResponseClosed,21 ResponseNotRead,22 StreamConsumed,23)Add response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 24–29why, one step back24from .utils import (25 get_reason_phrase,26 is_known_encoding,27 normalize_header_key,28 normalize_header_value,29)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 30why, one step back30Finessing interfaceTom Christiebefore adoptiond7619a9
line 31why, one step back31URLTypes = typing.Union["URL", str]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 32why, one step back32Finessing interfaceTom Christiebefore adoptiond7619a9
lines 33–38why, one step back33HeaderTypes = typing.Union[34 "Headers",35 typing.Dict[typing.AnyStr, typing.AnyStr],36 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],37]38Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 39why, one step back39ByteOrByteStream = typing.Union[bytes, typing.AsyncIterator[bytes]]Finessing interfaceTom Christiebefore adoptiond7619a9
lines 40–41why, one step back4041Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 42why, one step back42class URL:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 43why, one step back43 def __init__(self, url: URLTypes, allow_relative: bool = False) -> None:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 44why, one step back44 if isinstance(url, rfc3986.uri.URIReference):Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 45why, one step back45 self.components = urlAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 46–47why, one step back46 elif isinstance(url, str):47 self.components = rfc3986.api.uri_reference(url)Finessing interfaceTom Christiebefore adoptiond7619a9
lines 48–50why, one step back48 else:49 self.components = url.components50Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 51–56why, one step back51 # Handle IDNA domain names.52 if self.components.authority:53 idna_authority = self.components.authority.encode("idna").decode("ascii")54 if idna_authority != self.components.authority:55 self.components = self.components.copy_with(authority=idna_authority)56Fix docstringsTom Christiebefore adoption8a227c1
line 57why, one step back57 # Normalize scheme and domain name.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 58–60why, one step back58 self.components = self.components.normalize()5960 # Enforce absolute URLs by default.Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 61–66why, one step back61 if not allow_relative:62 if not self.scheme:63 raise InvalidURL("No scheme included in URL.")64 if self.scheme not in ("http", "https"):65 raise InvalidURL('URL scheme must be "http" or "https".')66 if not self.host:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 67why, one step back67 raise InvalidURL("No host included in URL.")Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 68–70why, one step back6869 @property70 def scheme(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 71why, one step back71 return self.components.scheme or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 72–73why, one step back7273 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 74–75why, one step back74 def authority(self) -> str:75 return self.components.authority or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 76–77why, one step back7677 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 78–79why, one step back78 def host(self) -> str:79 return self.components.host or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 80–85why, one step back8081 @property82 def port(self) -> int:83 port = self.components.port84 if port is None:85 return {"https": 443, "http": 80}[self.scheme]Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 86why, one step back86 return int(port)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 87–88why, one step back8788 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 89–96why, one step back89 def path(self) -> str:90 return self.components.path or "/"9192 @property93 def query(self) -> str:94 return self.components.query or ""9596 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 97why, one step back97 def full_path(self) -> str:Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
lines 98–100why, one step back98 path = self.path99 if self.query:100 path += "?" + self.queryMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 101–103why, one step back101 return path102103 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 104–107why, one step back104 def fragment(self) -> str:105 return self.components.fragment or ""106107 @propertyCarefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 108why, one step back108 def is_ssl(self) -> bool:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 109–111why, one step back109 return self.components.scheme == "https"110111 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 112–121why, one step back112 def is_absolute_url(self) -> bool:113 """114 Return `True` for absolute URLs such as 'http://example.com/path',115 and `False` for relative URLs such as '/path'.116 """117 # We don't use rfc3986's `is_absolute` because it treats118 # URLs with a fragment portion as not absolute.119 # What we actually care about is if the URL provides120 # a scheme and hostname to which connections should be made.121 return self.components.scheme and self.components.hostUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 122–123why, one step back122123 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 124–127why, one step back124 def is_relative_url(self) -> bool:125 return not self.is_absolute_url126127 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 128–130why, one step back128 def origin(self) -> "Origin":129 return Origin(self)130Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 131–134why, one step back131 def copy_with(self, **kwargs: typing.Any) -> "URL":132 return URL(self.components.copy_with(**kwargs))133134 def resolve_with(self, base_url: URLTypes) -> "URL":Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 135–138why, one step back135 """136 Return an absolute URL, using base_url as the base.137 """138 # We drop any fragment portion, because RFC 3986 strictlyFix docstringsTom Christiebefore adoption8a227c1
line 139why, one step back139 # treats URLs with a fragment portion as not being absolute URLs.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 140–141why, one step back140 base_url = URL(base_url).copy_with(fragment=None)141 return URL(self.components.resolve_with(base_url.components))Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 142why, one step back142Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 143–149why, one step back143 def __hash__(self) -> int:144 return hash(str(self))145146 def __eq__(self, other: typing.Any) -> bool:147 return isinstance(other, URL) and str(self) == str(other)148149 def __str__(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 150why, one step back150 return self.components.unsplit()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 151–158why, one step back151152 def __repr__(self) -> str:153 class_name = self.__class__.__name__154 url_str = str(self)155 return f"{class_name}({url_str!r})"156157158class Origin:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 159–160why, one step back159 def __init__(self, url: URLTypes) -> None:160 if not isinstance(url, URL):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 161why, one step back161 url = URL(url)Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 162why, one step back162 self.is_ssl = url.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 163why, one step back163 self.host = url.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 164–169why, one step back164 self.port = url.port165166 def __eq__(self, other: typing.Any) -> bool:167 return (168 isinstance(other, self.__class__)169 and self.is_ssl == other.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 170why, one step back170 and self.host == other.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 171–174why, one step back171 and self.port == other.port172 )173174 def __hash__(self) -> int:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 175why, one step back175 return hash((self.is_ssl, self.host, self.port))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 176–182why, one step back176177178class Headers(typing.MutableMapping[str, str]):179 """180 A case-insensitive multidict.181 """182Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 183why, one step back183 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 184–189why, one step back184 if headers is None:185 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]186 elif isinstance(headers, Headers):187 self._list = list(headers.raw)188 elif isinstance(headers, dict):189 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 190why, one step back190 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 191–194why, one step back191 for k, v in headers.items()192 ]193 else:194 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 195–196why, one step back195 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))196 for k, v in headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 197why, one step back197 ]Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 198why, one step back198 self._encoding = encodingMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 199–200why, one step back199200 @propertyRejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 201–229why, one step back201 def encoding(self) -> str:202 """203 Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be204 seen in the wild.205 """206 if self._encoding is None:207 for encoding in ["ascii", "utf-8"]:208 for key, value in self.raw:209 try:210 key.decode(encoding)211 value.decode(encoding)212 except UnicodeDecodeError:213 break214 else:215 # The else block runs if 'break' did not occur, meaning216 # all values fitted the encoding.217 self._encoding = encoding218 break219 else:220 # The ISO-8859-1 encoding covers all 256 code points in a byte,221 # so will never raise decode errors.222 self._encoding = "iso-8859-1"223 return self._encoding224225 @encoding.setter226 def encoding(self, value: str) -> None:227 self._encoding = value228229 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 230why, one step back230 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 231–234why, one step back231 """232 Returns a list of the raw header items, as byte pairs.233 May be mutated in-place.234 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 235–237why, one step back235 return self._list236237 def keys(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 238why, one step back238 return [key.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 239–240why, one step back239240 def values(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 241why, one step back241 return [value.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 242–244why, one step back242243 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore244 return [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 245why, one step back245 (key.decode(self.encoding), value.decode(self.encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 246–254why, one step back246 for key, value in self._list247 ]248249 def get(self, key: str, default: typing.Any = None) -> typing.Any:250 try:251 return self[key]252 except KeyError:253 return default254Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 255why, one step back255 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 256–262why, one step back256 """257 Return multiple header values.258 """259 get_header_key = key.lower().encode(self.encoding)260261 values = [262 item_value.decode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 263–266why, one step back263 for item_key, item_value in self._list264 if item_key == get_header_key265 ]266Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 267–274why, one step back267 if not split_commas:268 return values269270 split_values = []271 for value in values:272 split_values.extend([item.strip() for item in value.split(",")])273 return split_values274Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 275why, one step back275 def __getitem__(self, key: str) -> str:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 276–284why, one step back276 """277 Return a single header value.278279 If there are multiple headers with the same key, then we concatenate280 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2281 """282 normalized_key = key.lower().encode(self.encoding)283284 items = []Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 285why, one step back285 for header_key, header_value in self._list:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 286–291why, one step back286 if header_key == normalized_key:287 items.append(header_value.decode(self.encoding))288289 if items:290 return ", ".join(items)291Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 292–298why, one step back292 raise KeyError(key)293294 def __setitem__(self, key: str, value: str) -> None:295 """296 Set the header `key` to `value`, removing any duplicate entries.297 Retains insertion order.298 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 299–300why, one step back299 set_key = key.lower().encode(self.encoding)300 set_value = value.encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 301–319why, one step back301302 found_indexes = []303 for idx, (item_key, item_value) in enumerate(self._list):304 if item_key == set_key:305 found_indexes.append(idx)306307 for idx in reversed(found_indexes[1:]):308 del self._list[idx]309310 if found_indexes:311 idx = found_indexes[0]312 self._list[idx] = (set_key, set_value)313 else:314 self._list.append((set_key, set_value))315316 def __delitem__(self, key: str) -> None:317 """318 Remove the header `key`.319 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 320why, one step back320 del_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 321–330why, one step back321322 pop_indexes = []323 for idx, (item_key, item_value) in enumerate(self._list):324 if item_key == del_key:325 pop_indexes.append(idx)326327 for idx in reversed(pop_indexes):328 del self._list[idx]329330 def __contains__(self, key: typing.Any) -> bool:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 331why, one step back331 get_header_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 332–349why, one step back332 for header_key, header_value in self._list:333 if header_key == get_header_key:334 return True335 return False336337 def __iter__(self) -> typing.Iterator[typing.Any]:338 return iter(self.keys())339340 def __len__(self) -> int:341 return len(self._list)342343 def __eq__(self, other: typing.Any) -> bool:344 if not isinstance(other, Headers):345 return False346 return sorted(self._list) == sorted(other._list)347348 def __repr__(self) -> str:349 class_name = self.__class__.__name__Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 350–354why, one step back350351 encoding_str = ""352 if self.encoding != "ascii":353 encoding_str = f", encoding={self.encoding!r}"354Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 355–356why, one step back355 as_dict = dict(self.items())356 if len(as_dict) == len(self):Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 357–359why, one step back357 return f"{class_name}({as_dict!r}{encoding_str})"358 as_list = self.items()359 return f"{class_name}({as_list!r}{encoding_str})"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 360–368why, one step back360361362class Request:363 def __init__(364 self,365 method: str,366 url: typing.Union[str, URL],367 *,368 headers: HeaderTypes = None,Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 369why, one step back369 content: ByteOrByteStream = b"",Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 370–372why, one step back370 ):371 self.method = method.upper()372 self.url = URL(url) if isinstance(url, str) else urlPrefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 373why, one step back373 if isinstance(content, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 374why, one step back374 self.is_streaming = FalsePrefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 375why, one step back375 self.content = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 376–377why, one step back376 else:377 self.is_streaming = TruePrefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 378why, one step back378 self.content_aiter = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 379–384why, one step back379 self.headers = Headers(headers)380381 async def read(self) -> bytes:382 """383 Read and return the response content.384 """Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 385–386why, one step back385 if not hasattr(self, "content"):386 content = b""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 387why, one step back387 async for part in self.stream():Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 388–390why, one step back388 content += part389 self.content = content390 return self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 391–393why, one step back391392 async def stream(self) -> typing.AsyncIterator[bytes]:393 if self.is_streaming:Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 394why, one step back394 async for part in self.content_aiter:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 395why, one step back395 yield partPrefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 396–397why, one step back396 elif self.content:397 yield self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 398–399why, one step back398399 def prepare(self) -> None:Response.contentTom Christiebefore adoption4c55113
lines 400–406why, one step back400 """401 Adds in any default headers. When using the `Client`, this will402 end up being called into by the `prepare_request()` stage.403404 You can omit this behavior by calling `Client.send()` with an405 explicitly built `Request` instance.406 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 407–414why, one step back407 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]408409 has_host = "host" in self.headers410 has_content_length = (411 "content-length" in self.headers or "transfer-encoding" in self.headers412 )413 has_accept_encoding = "accept-encoding" in self.headers414Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 415–416why, one step back415 if not has_host and self.url.authority:416 auto_headers.append((b"host", self.url.authority.encode("ascii")))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 417–419why, one step back417 if not has_content_length:418 if self.is_streaming:419 auto_headers.append((b"transfer-encoding", b"chunked"))Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 420–421why, one step back420 elif self.content:421 content_length = str(len(self.content)).encode()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 422–428why, one step back422 auto_headers.append((b"content-length", content_length))423 if not has_accept_encoding:424 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))425426 for item in reversed(auto_headers):427 self.headers.raw.insert(0, item)428Still truckin' onTom Christiebefore adoption6cb5c0d
lines 429–432why, one step back429 def __repr__(self) -> str:430 class_name = self.__class__.__name__431 url = str(self.url)432 return f"<{class_name}({self.method}, {url})>"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 433why, one step back433Still truckin' onTom Christiebefore adoption6cb5c0d
line 434why, one step back434Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 435–439why, one step back435class Response:436 def __init__(437 self,438 status_code: int,439 *,Finessing interfaceTom Christiebefore adoptiond7619a9
lines 440–442why, one step back440 reason_phrase: str = None,441 protocol: str = None,442 headers: HeaderTypes = None,Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 443why, one step back443 content: ByteOrByteStream = b"",Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 444–447why, one step back444 on_close: typing.Callable = None,445 request: Request = None,446 history: typing.List["Response"] = None,447 ):Truckin' onTom Christiebefore adoption6b60d95
lines 448–449why, one step back448 try:449 # Use a StatusCode IntEnum if possible, for a nicer representation.Still truckin' onTom Christiebefore adoption6cb5c0d
line 450why, one step back450 self.status_code = codes(status_code) # type: intTruckin' onTom Christiebefore adoption6b60d95
lines 451–452why, one step back451 except ValueError:452 self.status_code = status_codeResponse.contentTom Christiebefore adoption4c55113
line 453why, one step back453 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 454–456why, one step back454 self.protocol = protocol455 self.headers = Headers(headers)456Response.contentTom Christiebefore adoption4c55113
line 457why, one step back457 if isinstance(content, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 458why, one step back458 self.is_closed = TrueResponse.contentTom Christiebefore adoption4c55113
lines 459–460why, one step back459 self.is_stream_consumed = True460 self._raw_content = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 461why, one step back461 else:Response.contentTom Christiebefore adoption4c55113
lines 462–464why, one step back462 self.is_closed = False463 self.is_stream_consumed = False464 self._raw_stream = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 465why, one step back465Response.contentTom Christiebefore adoption4c55113
line 466why, one step back466 self.on_close = on_closeMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 467–468why, one step back467 self.request = request468 self.history = [] if history is None else list(history)response.next()Tom Christiebefore adoptiond652479
line 469why, one step back469 self.next = None # typing.Optional[typing.Callable]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 470–472why, one step back470471 @property472 def url(self) -> typing.Optional[URL]:Clean up response interfaceTom Christiebefore adoption4d908d0
lines 473–477why, one step back473 """474 Returns the URL for which the request was made.475476 Requires that `request` was provided when instantiating the response.477 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 478why, one step back478 return None if self.request is None else self.request.urlClean up response interfaceTom Christiebefore adoption4d908d0
lines 479–480why, one step back479480 @propertyResponse.contentTom Christiebefore adoption4c55113
lines 481–483why, one step back481 def content(self) -> bytes:482 if not hasattr(self, "_content"):483 if hasattr(self, "_raw_content"):Add response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 484–486why, one step back484 content = self.decoder.decode(self._raw_content)485 content += self.decoder.flush()486 self._content = contentResponse.contentTom Christiebefore adoption4c55113
lines 487–489why, one step back487 else:488 raise ResponseNotRead()489 return self._contentAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 490–525why, one step back490491 @property492 def text(self) -> str:493 if not hasattr(self, "_text"):494 content = self.content495 if not content:496 self._text = ""497 else:498 encoding = self.encoding499 self._text = content.decode(encoding, errors="replace")500 return self._text501502 @property503 def encoding(self) -> str:504 if not hasattr(self, "_encoding"):505 encoding = self.charset_encoding506 if encoding is None or not is_known_encoding(encoding):507 encoding = self.apparent_encoding508 if encoding is None or not is_known_encoding(encoding):509 encoding = "utf-8"510 self._encoding = encoding511 return self._encoding512513 @encoding.setter514 def encoding(self, value: str) -> None:515 self._encoding = value516517 @property518 def charset_encoding(self) -> typing.Optional[str]:519 """520 Return the encoding, as specified by the Content-Type header.521 """522 content_type = self.headers.get("Content-Type")523 if content_type is None:524 return None525Truckin' onTom Christiebefore adoption0ca1c84
lines 526–530why, one step back526 parsed = cgi.parse_header(content_type)527 media_type, params = parsed[0], parsed[-1]528 if "charset" in params:529 return params["charset"].strip("'\"")530Media types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 531–533why, one step back531 # RFC 2616 specifies that 'iso-8859-1' should be used as the default532 # for 'text/*' media types, if no charset is provided.533 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1Truckin' onTom Christiebefore adoption0ca1c84
lines 534–537why, one step back534 if media_type.startswith("text/"):535 return "iso-8859-1"536537 return NoneAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 538–544why, one step back538539 @property540 def apparent_encoding(self) -> typing.Optional[str]:541 """542 Return the encoding, as it appears to autodetection.543 """544 return chardet.detect(self.content)["encoding"]Response.contentTom Christiebefore adoption4c55113
lines 545–546why, one step back545546 @propertyClean up response interfaceTom Christiebefore adoption4d908d0
lines 547–553why, one step back547 def decoder(self) -> Decoder:548 """549 Returns a decoder instance which can be used to decode the raw byte550 content, depending on the Content-Encoding used in the response.551 """552 if not hasattr(self, "_decoder"):553 decoders = [] # type: typing.List[Decoder]Response.contentTom Christiebefore adoption4c55113
line 554why, one step back554 values = self.headers.getlist("content-encoding", split_commas=True)Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 555–557why, one step back555 for value in values:556 value = value.strip().lower()557 decoder_cls = SUPPORTED_DECODERS[value]Clean up response interfaceTom Christiebefore adoption4d908d0
lines 558–567why, one step back558 decoders.append(decoder_cls())559560 if len(decoders) == 1:561 self._decoder = decoders[0]562 elif len(decoders) > 1:563 self._decoder = MultiDecoder(decoders)564 else:565 self._decoder = IdentityDecoder()566567 return self._decoderMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 568–572why, one step back568569 async def read(self) -> bytes:570 """571 Read and return the response content.572 """Response.contentTom Christiebefore adoption4c55113
lines 573–574why, one step back573 if not hasattr(self, "_content"):574 content = b""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 575why, one step back575 async for part in self.stream():Response.contentTom Christiebefore adoption4c55113
lines 576–578why, one step back576 content += part577 self._content = content578 return self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 579–584why, one step back579580 async def stream(self) -> typing.AsyncIterator[bytes]:581 """582 A byte-iterator over the decoded response content.583 This allows us to handle gzip, deflate, and brotli encoded responses.584 """Response.contentTom Christiebefore adoption4c55113
lines 585–586why, one step back585 if hasattr(self, "_content"):586 yield self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 587–595why, one step back587 else:588 async for chunk in self.raw():589 yield self.decoder.decode(chunk)590 yield self.decoder.flush()591592 async def raw(self) -> typing.AsyncIterator[bytes]:593 """594 A byte-iterator over the raw response content.595 """Response.contentTom Christiebefore adoption4c55113
lines 596–607why, one step back596 if hasattr(self, "_raw_content"):597 yield self._raw_content598 else:599 if self.is_stream_consumed:600 raise StreamConsumed()601 if self.is_closed:602 raise ResponseClosed()603604 self.is_stream_consumed = True605 async for part in self._raw_stream:606 yield part607 await self.close()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 608–621why, one step back608609 async def close(self) -> None:610 """611 Close the response and release the connection.612 Automatically called if the response body is read to completion.613 """614 if not self.is_closed:615 self.is_closed = True616 if self.on_close is not None:617 await self.on_close()618619 @property620 def is_redirect(self) -> bool:621 return (Finessing interfaceTom Christiebefore adoptiond7619a9
lines 622–630why, one step back622 self.status_code623 in (624 codes.moved_permanently,625 codes.found,626 codes.see_other,627 codes.temporary_redirect,628 codes.permanent_redirect,629 )630 and "location" in self.headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 631why, one step back631 )Still truckin' onTom Christiebefore adoption6cb5c0d
lines 632–635why, one step back632633 def __repr__(self) -> str:634 class_name = self.__class__.__name__635 return f"<{class_name}(status_code={self.status_code})>"Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 636–654why, one step back636637 def raise_for_status(self) -> None:638 """639 Raise the `HttpError` if one occurred.640 """641 message = (642 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"643 "For more information check: https://httpstatuses.com/{0.status_code}"644 )645646 if 400 <= self.status_code < 500:647 message = message.format(self, error_type="Client Error")648 elif 500 <= self.status_code < 600:649 message = message.format(self, error_type="Server Error")650 else:651 message = ""652653 if message:654 raise HttpError(message)