models.py
This file
Path
httpcore/models.py
608 lines · 19.0 KiB · Python
Last changed by
Add idna support. More tests.Tom Christiebefore adoptionb948798
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
lines 8–15why, one step back8from .config import SSLConfig, TimeoutConfig9from .decoders import (10 ACCEPT_ENCODING,11 SUPPORTED_DECODERS,12 Decoder,13 IdentityDecoder,14 MultiDecoder,15)Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 16why, one step back16from .exceptions import InvalidURL, ResponseClosed, ResponseNotRead, StreamConsumedFinessing interfaceTom Christiebefore adoptiond7619a9
line 17why, one step back17from .status_codes import codesAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 18–23why, one step back18from .utils import (19 get_reason_phrase,20 is_known_encoding,21 normalize_header_key,22 normalize_header_value,23)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 24why, one step back24Finessing interfaceTom Christiebefore adoptiond7619a9
line 25why, one step back25URLTypes = typing.Union["URL", str]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 26why, one step back26Finessing interfaceTom Christiebefore adoptiond7619a9
lines 27–32why, one step back27HeaderTypes = typing.Union[28 "Headers",29 typing.Dict[typing.AnyStr, typing.AnyStr],30 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],31]32Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 33why, one step back33ByteOrByteStream = typing.Union[bytes, typing.AsyncIterator[bytes]]Finessing interfaceTom Christiebefore adoptiond7619a9
lines 34–35why, one step back3435Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 36why, one step back36class URL:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 37why, one step back37 def __init__(self, url: URLTypes, allow_relative: bool = False) -> None:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 38why, one step back38 if isinstance(url, rfc3986.uri.URIReference):Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 39why, one step back39 self.components = urlAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 40–41why, one step back40 elif isinstance(url, str):41 self.components = rfc3986.api.uri_reference(url)Finessing interfaceTom Christiebefore adoptiond7619a9
lines 42–44why, one step back42 else:43 self.components = url.components44Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 45–54why, one step back45 # Handle IDNA domain names.46 if self.components.authority:47 idna_authority = self.components.authority.encode("idna").decode("ascii")48 if idna_authority != self.components.authority:49 self.components = self.components.copy_with(authority=idna_authority)5051 # Normalize schema and domain name.52 self.components = self.components.normalize()5354 # Enforce absolute URLs by default.Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 55–60why, one step back55 if not allow_relative:56 if not self.scheme:57 raise InvalidURL("No scheme included in URL.")58 if self.scheme not in ("http", "https"):59 raise InvalidURL('URL scheme must be "http" or "https".')60 if not self.host:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 61why, one step back61 raise InvalidURL("No host included in URL.")Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 62–64why, one step back6263 @property64 def scheme(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 65why, one step back65 return self.components.scheme or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 66–67why, one step back6667 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 68–69why, one step back68 def authority(self) -> str:69 return self.components.authority or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 70–72why, one step back7071 @property72 def path(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 73why, one step back73 return self.components.path or "/"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 74–76why, one step back7475 @property76 def query(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 77why, one step back77 return self.components.query or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 78–80why, one step back7879 @property80 def fragment(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 81why, one step back81 return self.components.fragment or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 82–83why, one step back8283 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 84–85why, one step back84 def host(self) -> str:85 return self.components.host or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 86–106why, one step back8687 @property88 def port(self) -> int:89 port = self.components.port90 if port is None:91 return {"https": 443, "http": 80}[self.scheme]92 return port9394 @property95 def full_path(self) -> str:96 path = self.path or "/"97 query = self.query98 if query:99 return path + "?" + query100 return path101102 @property103 def is_secure(self) -> bool:104 return self.components.scheme == "https"105106 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 107–116why, one step back107 def is_absolute_url(self) -> bool:108 """109 Return `True` for absolute URLs such as 'http://example.com/path',110 and `False` for relative URLs such as '/path'.111 """112 # We don't use rfc3986's `is_absolute` because it treats113 # URLs with a fragment portion as not absolute.114 # What we actually care about is if the URL provides115 # a scheme and hostname to which connections should be made.116 return self.components.scheme and self.components.hostUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 117–118why, one step back117118 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 119–122why, one step back119 def is_relative_url(self) -> bool:120 return not self.is_absolute_url121122 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 123–125why, one step back123 def origin(self) -> "Origin":124 return Origin(self)125Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 126–129why, one step back126 def copy_with(self, **kwargs: typing.Any) -> "URL":127 return URL(self.components.copy_with(**kwargs))128129 def resolve_with(self, base_url: URLTypes) -> "URL":Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 130–137why, one step back130 """131 Return an absolute URL, using base_url as the base.132 """133 # We drop any fragment portion, because RFC 3986 strictly134 # treats URLs with a fragment portion as not being absolute URLs,135 # but we want to treat them as such for the purposes of136 base_url = URL(base_url).copy_with(fragment=None)137 return URL(self.components.resolve_with(base_url.components))Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 138why, one step back138Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 139–145why, one step back139 def __hash__(self) -> int:140 return hash(str(self))141142 def __eq__(self, other: typing.Any) -> bool:143 return isinstance(other, URL) and str(self) == str(other)144145 def __str__(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 146why, one step back146 return self.components.unsplit()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 147–154why, one step back147148 def __repr__(self) -> str:149 class_name = self.__class__.__name__150 url_str = str(self)151 return f"{class_name}({url_str!r})"152153154class Origin:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 155–156why, one step back155 def __init__(self, url: URLTypes) -> None:156 if not isinstance(url, URL):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 157–158why, one step back157 url = URL(url)158 self.is_ssl = url.scheme == "https"Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 159why, one step back159 self.host = url.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 160–165why, one step back160 self.port = url.port161162 def __eq__(self, other: typing.Any) -> bool:163 return (164 isinstance(other, self.__class__)165 and self.is_ssl == other.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 166why, one step back166 and self.host == other.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 167–170why, one step back167 and self.port == other.port168 )169170 def __hash__(self) -> int:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 171why, one step back171 return hash((self.is_ssl, self.host, self.port))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 172–178why, one step back172173174class Headers(typing.MutableMapping[str, str]):175 """176 A case-insensitive multidict.177 """178Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 179why, one step back179 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 180–185why, one step back180 if headers is None:181 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]182 elif isinstance(headers, Headers):183 self._list = list(headers.raw)184 elif isinstance(headers, dict):185 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 186why, one step back186 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 187–190why, one step back187 for k, v in headers.items()188 ]189 else:190 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 191–192why, one step back191 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))192 for k, v in headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 193why, one step back193 ]Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 194why, one step back194 self._encoding = encodingMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 195–196why, one step back195196 @propertyRejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 197–225why, one step back197 def encoding(self) -> str:198 """199 Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be200 seen in the wild.201 """202 if self._encoding is None:203 for encoding in ["ascii", "utf-8"]:204 for key, value in self.raw:205 try:206 key.decode(encoding)207 value.decode(encoding)208 except UnicodeDecodeError:209 break210 else:211 # The else block runs if 'break' did not occur, meaning212 # all values fitted the encoding.213 self._encoding = encoding214 break215 else:216 # The ISO-8859-1 encoding covers all 256 code points in a byte,217 # so will never raise decode errors.218 self._encoding = "iso-8859-1"219 return self._encoding220221 @encoding.setter222 def encoding(self, value: str) -> None:223 self._encoding = value224225 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 226why, one step back226 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 227–230why, one step back227 """228 Returns a list of the raw header items, as byte pairs.229 May be mutated in-place.230 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 231–233why, one step back231 return self._list232233 def keys(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 234why, one step back234 return [key.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 235–236why, one step back235236 def values(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 237why, one step back237 return [value.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 238–240why, one step back238239 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore240 return [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 241why, one step back241 (key.decode(self.encoding), value.decode(self.encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 242–250why, one step back242 for key, value in self._list243 ]244245 def get(self, key: str, default: typing.Any = None) -> typing.Any:246 try:247 return self[key]248 except KeyError:249 return default250Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 251why, one step back251 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 252–258why, one step back252 """253 Return multiple header values.254 """255 get_header_key = key.lower().encode(self.encoding)256257 values = [258 item_value.decode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 259–262why, one step back259 for item_key, item_value in self._list260 if item_key == get_header_key261 ]262Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 263–270why, one step back263 if not split_commas:264 return values265266 split_values = []267 for value in values:268 split_values.extend([item.strip() for item in value.split(",")])269 return split_values270Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 271why, one step back271 def __getitem__(self, key: str) -> str:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 272–280why, one step back272 """273 Return a single header value.274275 If there are multiple headers with the same key, then we concatenate276 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2277 """278 normalized_key = key.lower().encode(self.encoding)279280 items = []Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 281why, one step back281 for header_key, header_value in self._list:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 282–287why, one step back282 if header_key == normalized_key:283 items.append(header_value.decode(self.encoding))284285 if items:286 return ", ".join(items)287Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 288–294why, one step back288 raise KeyError(key)289290 def __setitem__(self, key: str, value: str) -> None:291 """292 Set the header `key` to `value`, removing any duplicate entries.293 Retains insertion order.294 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 295–296why, one step back295 set_key = key.lower().encode(self.encoding)296 set_value = value.encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 297–315why, one step back297298 found_indexes = []299 for idx, (item_key, item_value) in enumerate(self._list):300 if item_key == set_key:301 found_indexes.append(idx)302303 for idx in reversed(found_indexes[1:]):304 del self._list[idx]305306 if found_indexes:307 idx = found_indexes[0]308 self._list[idx] = (set_key, set_value)309 else:310 self._list.append((set_key, set_value))311312 def __delitem__(self, key: str) -> None:313 """314 Remove the header `key`.315 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 316why, one step back316 del_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 317–326why, one step back317318 pop_indexes = []319 for idx, (item_key, item_value) in enumerate(self._list):320 if item_key == del_key:321 pop_indexes.append(idx)322323 for idx in reversed(pop_indexes):324 del self._list[idx]325326 def __contains__(self, key: typing.Any) -> bool:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 327why, one step back327 get_header_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 328–345why, one step back328 for header_key, header_value in self._list:329 if header_key == get_header_key:330 return True331 return False332333 def __iter__(self) -> typing.Iterator[typing.Any]:334 return iter(self.keys())335336 def __len__(self) -> int:337 return len(self._list)338339 def __eq__(self, other: typing.Any) -> bool:340 if not isinstance(other, Headers):341 return False342 return sorted(self._list) == sorted(other._list)343344 def __repr__(self) -> str:345 class_name = self.__class__.__name__Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 346–350why, one step back346347 encoding_str = ""348 if self.encoding != "ascii":349 encoding_str = f", encoding={self.encoding!r}"350Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 351–352why, one step back351 as_dict = dict(self.items())352 if len(as_dict) == len(self):Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 353–355why, one step back353 return f"{class_name}({as_dict!r}{encoding_str})"354 as_list = self.items()355 return f"{class_name}({as_list!r}{encoding_str})"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 356–364why, one step back356357358class Request:359 def __init__(360 self,361 method: str,362 url: typing.Union[str, URL],363 *,364 headers: HeaderTypes = None,Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 365why, one step back365 content: ByteOrByteStream = b"",Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 366–368why, one step back366 ):367 self.method = method.upper()368 self.url = URL(url) if isinstance(url, str) else urlPrefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 369why, one step back369 if isinstance(content, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 370why, one step back370 self.is_streaming = FalsePrefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 371why, one step back371 self.content = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 372–373why, one step back372 else:373 self.is_streaming = TruePrefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 374why, one step back374 self.content_aiter = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 375–380why, one step back375 self.headers = Headers(headers)376377 async def read(self) -> bytes:378 """379 Read and return the response content.380 """Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 381–382why, one step back381 if not hasattr(self, "content"):382 content = b""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 383why, one step back383 async for part in self.stream():Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 384–386why, one step back384 content += part385 self.content = content386 return self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 387–389why, one step back387388 async def stream(self) -> typing.AsyncIterator[bytes]:389 if self.is_streaming:Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 390why, one step back390 async for part in self.content_aiter:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 391why, one step back391 yield partPrefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 392–393why, one step back392 elif self.content:393 yield self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 394–395why, one step back394395 def prepare(self) -> None:Response.contentTom Christiebefore adoption4c55113
lines 396–402why, one step back396 """397 Adds in any default headers. When using the `Client`, this will398 end up being called into by the `prepare_request()` stage.399400 You can omit this behavior by calling `Client.send()` with an401 explicitly built `Request` instance.402 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 403–410why, one step back403 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]404405 has_host = "host" in self.headers406 has_content_length = (407 "content-length" in self.headers or "transfer-encoding" in self.headers408 )409 has_accept_encoding = "accept-encoding" in self.headers410Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 411–412why, one step back411 if not has_host and self.url.authority:412 auto_headers.append((b"host", self.url.authority.encode("ascii")))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 413–415why, one step back413 if not has_content_length:414 if self.is_streaming:415 auto_headers.append((b"transfer-encoding", b"chunked"))Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 416–417why, one step back416 elif self.content:417 content_length = str(len(self.content)).encode()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 418–430why, one step back418 auto_headers.append((b"content-length", content_length))419 if not has_accept_encoding:420 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))421422 for item in reversed(auto_headers):423 self.headers.raw.insert(0, item)424425426class Response:427 def __init__(428 self,429 status_code: int,430 *,Finessing interfaceTom Christiebefore adoptiond7619a9
lines 431–433why, one step back431 reason_phrase: str = None,432 protocol: str = None,433 headers: HeaderTypes = None,Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 434why, one step back434 content: ByteOrByteStream = b"",Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 435–439why, one step back435 on_close: typing.Callable = None,436 request: Request = None,437 history: typing.List["Response"] = None,438 ):439 self.status_code = status_codeResponse.contentTom Christiebefore adoption4c55113
line 440why, one step back440 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 441–443why, one step back441 self.protocol = protocol442 self.headers = Headers(headers)443Response.contentTom Christiebefore adoption4c55113
line 444why, one step back444 if isinstance(content, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 445why, one step back445 self.is_closed = TrueResponse.contentTom Christiebefore adoption4c55113
lines 446–447why, one step back446 self.is_stream_consumed = True447 self._raw_content = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 448why, one step back448 else:Response.contentTom Christiebefore adoption4c55113
lines 449–451why, one step back449 self.is_closed = False450 self.is_stream_consumed = False451 self._raw_stream = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 452why, one step back452Response.contentTom Christiebefore adoption4c55113
line 453why, one step back453 self.on_close = on_closeMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 454–455why, one step back454 self.request = request455 self.history = [] if history is None else list(history)response.next()Tom Christiebefore adoptiond652479
line 456why, one step back456 self.next = None # typing.Optional[typing.Callable]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 457–459why, one step back457458 @property459 def url(self) -> typing.Optional[URL]:Clean up response interfaceTom Christiebefore adoption4d908d0
lines 460–464why, one step back460 """461 Returns the URL for which the request was made.462463 Requires that `request` was provided when instantiating the response.464 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 465why, one step back465 return None if self.request is None else self.request.urlClean up response interfaceTom Christiebefore adoption4d908d0
lines 466–467why, one step back466467 @propertyResponse.contentTom Christiebefore adoption4c55113
lines 468–470why, one step back468 def content(self) -> bytes:469 if not hasattr(self, "_content"):470 if hasattr(self, "_raw_content"):Add response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 471–473why, one step back471 content = self.decoder.decode(self._raw_content)472 content += self.decoder.flush()473 self._content = contentResponse.contentTom Christiebefore adoption4c55113
lines 474–476why, one step back474 else:475 raise ResponseNotRead()476 return self._contentAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 477–521why, one step back477478 @property479 def text(self) -> str:480 if not hasattr(self, "_text"):481 content = self.content482 if not content:483 self._text = ""484 else:485 encoding = self.encoding486 self._text = content.decode(encoding, errors="replace")487 return self._text488489 @property490 def encoding(self) -> str:491 if not hasattr(self, "_encoding"):492 encoding = self.charset_encoding493 if encoding is None or not is_known_encoding(encoding):494 encoding = self.apparent_encoding495 if encoding is None or not is_known_encoding(encoding):496 encoding = "utf-8"497 self._encoding = encoding498 return self._encoding499500 @encoding.setter501 def encoding(self, value: str) -> None:502 self._encoding = value503504 @property505 def charset_encoding(self) -> typing.Optional[str]:506 """507 Return the encoding, as specified by the Content-Type header.508 """509 content_type = self.headers.get("Content-Type")510 if content_type is None:511 return None512513 parsed = cgi.parse_header(content_type)[-1]514 return parsed.get("charset")515516 @property517 def apparent_encoding(self) -> typing.Optional[str]:518 """519 Return the encoding, as it appears to autodetection.520 """521 return chardet.detect(self.content)["encoding"]Response.contentTom Christiebefore adoption4c55113
lines 522–523why, one step back522523 @propertyClean up response interfaceTom Christiebefore adoption4d908d0
lines 524–530why, one step back524 def decoder(self) -> Decoder:525 """526 Returns a decoder instance which can be used to decode the raw byte527 content, depending on the Content-Encoding used in the response.528 """529 if not hasattr(self, "_decoder"):530 decoders = [] # type: typing.List[Decoder]Response.contentTom Christiebefore adoption4c55113
line 531why, one step back531 values = self.headers.getlist("content-encoding", split_commas=True)Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 532–534why, one step back532 for value in values:533 value = value.strip().lower()534 decoder_cls = SUPPORTED_DECODERS[value]Clean up response interfaceTom Christiebefore adoption4d908d0
lines 535–544why, one step back535 decoders.append(decoder_cls())536537 if len(decoders) == 1:538 self._decoder = decoders[0]539 elif len(decoders) > 1:540 self._decoder = MultiDecoder(decoders)541 else:542 self._decoder = IdentityDecoder()543544 return self._decoderMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 545–549why, one step back545546 async def read(self) -> bytes:547 """548 Read and return the response content.549 """Response.contentTom Christiebefore adoption4c55113
lines 550–551why, one step back550 if not hasattr(self, "_content"):551 content = b""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 552why, one step back552 async for part in self.stream():Response.contentTom Christiebefore adoption4c55113
lines 553–555why, one step back553 content += part554 self._content = content555 return self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 556–561why, one step back556557 async def stream(self) -> typing.AsyncIterator[bytes]:558 """559 A byte-iterator over the decoded response content.560 This allows us to handle gzip, deflate, and brotli encoded responses.561 """Response.contentTom Christiebefore adoption4c55113
lines 562–563why, one step back562 if hasattr(self, "_content"):563 yield self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 564–572why, one step back564 else:565 async for chunk in self.raw():566 yield self.decoder.decode(chunk)567 yield self.decoder.flush()568569 async def raw(self) -> typing.AsyncIterator[bytes]:570 """571 A byte-iterator over the raw response content.572 """Response.contentTom Christiebefore adoption4c55113
lines 573–584why, one step back573 if hasattr(self, "_raw_content"):574 yield self._raw_content575 else:576 if self.is_stream_consumed:577 raise StreamConsumed()578 if self.is_closed:579 raise ResponseClosed()580581 self.is_stream_consumed = True582 async for part in self._raw_stream:583 yield part584 await self.close()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 585–598why, one step back585586 async def close(self) -> None:587 """588 Close the response and release the connection.589 Automatically called if the response body is read to completion.590 """591 if not self.is_closed:592 self.is_closed = True593 if self.on_close is not None:594 await self.on_close()595596 @property597 def is_redirect(self) -> bool:598 return (Finessing interfaceTom Christiebefore adoptiond7619a9
lines 599–607why, one step back599 self.status_code600 in (601 codes.moved_permanently,602 codes.found,603 codes.see_other,604 codes.temporary_redirect,605 codes.permanent_redirect,606 )607 and "location" in self.headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 608why, one step back608 )