models.py
This file
Path
httpcore/models.py
629 lines · 19.7 KiB · Python
Last changed by
Fix docstringsTom Christiebefore adoption8a227c1
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)Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 17why, one step back17from .exceptions import InvalidURL, ResponseClosed, ResponseNotRead, StreamConsumedAdd 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–50why, 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)50Fix docstringsTom Christiebefore adoption8a227c1
line 51why, one step back51 # Normalize scheme and domain name.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 52–54why, one step back52 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–71why, one step back7071 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 72–73why, one step back72 def host(self) -> str:73 return self.components.host or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 74–79why, one step back7475 @property76 def port(self) -> int:77 port = self.components.port78 if port is None:79 return {"https": 443, "http": 80}[self.scheme]Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 80why, one step back80 return int(port)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 81–82why, one step back8182 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 83–90why, one step back83 def path(self) -> str:84 return self.components.path or "/"8586 @property87 def query(self) -> str:88 return self.components.query or ""8990 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 91why, one step back91 def full_path(self) -> str:Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
lines 92–94why, one step back92 path = self.path93 if self.query:94 path += "?" + self.queryMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 95–97why, one step back95 return path9697 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 98–101why, one step back98 def fragment(self) -> str:99 return self.components.fragment or ""100101 @propertyCarefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 102why, one step back102 def is_ssl(self) -> bool:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 103–105why, one step back103 return self.components.scheme == "https"104105 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 106–115why, one step back106 def is_absolute_url(self) -> bool:107 """108 Return `True` for absolute URLs such as 'http://example.com/path',109 and `False` for relative URLs such as '/path'.110 """111 # We don't use rfc3986's `is_absolute` because it treats112 # URLs with a fragment portion as not absolute.113 # What we actually care about is if the URL provides114 # a scheme and hostname to which connections should be made.115 return self.components.scheme and self.components.hostUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 116–117why, one step back116117 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 118–121why, one step back118 def is_relative_url(self) -> bool:119 return not self.is_absolute_url120121 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 122–124why, one step back122 def origin(self) -> "Origin":123 return Origin(self)124Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 125–128why, one step back125 def copy_with(self, **kwargs: typing.Any) -> "URL":126 return URL(self.components.copy_with(**kwargs))127128 def resolve_with(self, base_url: URLTypes) -> "URL":Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 129–132why, one step back129 """130 Return an absolute URL, using base_url as the base.131 """132 # We drop any fragment portion, because RFC 3986 strictlyFix docstringsTom Christiebefore adoption8a227c1
line 133why, one step back133 # treats URLs with a fragment portion as not being absolute URLs.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 134–135why, one step back134 base_url = URL(base_url).copy_with(fragment=None)135 return URL(self.components.resolve_with(base_url.components))Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 136why, one step back136Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 137–143why, one step back137 def __hash__(self) -> int:138 return hash(str(self))139140 def __eq__(self, other: typing.Any) -> bool:141 return isinstance(other, URL) and str(self) == str(other)142143 def __str__(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 144why, one step back144 return self.components.unsplit()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 145–152why, one step back145146 def __repr__(self) -> str:147 class_name = self.__class__.__name__148 url_str = str(self)149 return f"{class_name}({url_str!r})"150151152class Origin:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 153–154why, one step back153 def __init__(self, url: URLTypes) -> None:154 if not isinstance(url, URL):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 155why, one step back155 url = URL(url)Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 156why, one step back156 self.is_ssl = url.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 157why, one step back157 self.host = url.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 158–163why, one step back158 self.port = url.port159160 def __eq__(self, other: typing.Any) -> bool:161 return (162 isinstance(other, self.__class__)163 and self.is_ssl == other.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 164why, one step back164 and self.host == other.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 165–168why, one step back165 and self.port == other.port166 )167168 def __hash__(self) -> int:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 169why, one step back169 return hash((self.is_ssl, self.host, self.port))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 170–176why, one step back170171172class Headers(typing.MutableMapping[str, str]):173 """174 A case-insensitive multidict.175 """176Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 177why, one step back177 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 178–183why, one step back178 if headers is None:179 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]180 elif isinstance(headers, Headers):181 self._list = list(headers.raw)182 elif isinstance(headers, dict):183 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 184why, one step back184 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 185–188why, one step back185 for k, v in headers.items()186 ]187 else:188 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 189–190why, one step back189 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))190 for k, v in headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 191why, one step back191 ]Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 192why, one step back192 self._encoding = encodingMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 193–194why, one step back193194 @propertyRejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 195–223why, one step back195 def encoding(self) -> str:196 """197 Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be198 seen in the wild.199 """200 if self._encoding is None:201 for encoding in ["ascii", "utf-8"]:202 for key, value in self.raw:203 try:204 key.decode(encoding)205 value.decode(encoding)206 except UnicodeDecodeError:207 break208 else:209 # The else block runs if 'break' did not occur, meaning210 # all values fitted the encoding.211 self._encoding = encoding212 break213 else:214 # The ISO-8859-1 encoding covers all 256 code points in a byte,215 # so will never raise decode errors.216 self._encoding = "iso-8859-1"217 return self._encoding218219 @encoding.setter220 def encoding(self, value: str) -> None:221 self._encoding = value222223 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 224why, one step back224 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 225–228why, one step back225 """226 Returns a list of the raw header items, as byte pairs.227 May be mutated in-place.228 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 229–231why, one step back229 return self._list230231 def keys(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 232why, one step back232 return [key.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 233–234why, one step back233234 def values(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 235why, one step back235 return [value.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 236–238why, one step back236237 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore238 return [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 239why, one step back239 (key.decode(self.encoding), value.decode(self.encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 240–248why, one step back240 for key, value in self._list241 ]242243 def get(self, key: str, default: typing.Any = None) -> typing.Any:244 try:245 return self[key]246 except KeyError:247 return default248Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 249why, one step back249 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 250–256why, one step back250 """251 Return multiple header values.252 """253 get_header_key = key.lower().encode(self.encoding)254255 values = [256 item_value.decode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 257–260why, one step back257 for item_key, item_value in self._list258 if item_key == get_header_key259 ]260Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 261–268why, one step back261 if not split_commas:262 return values263264 split_values = []265 for value in values:266 split_values.extend([item.strip() for item in value.split(",")])267 return split_values268Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 269why, one step back269 def __getitem__(self, key: str) -> str:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 270–278why, one step back270 """271 Return a single header value.272273 If there are multiple headers with the same key, then we concatenate274 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2275 """276 normalized_key = key.lower().encode(self.encoding)277278 items = []Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 279why, one step back279 for header_key, header_value in self._list:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 280–285why, one step back280 if header_key == normalized_key:281 items.append(header_value.decode(self.encoding))282283 if items:284 return ", ".join(items)285Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 286–292why, one step back286 raise KeyError(key)287288 def __setitem__(self, key: str, value: str) -> None:289 """290 Set the header `key` to `value`, removing any duplicate entries.291 Retains insertion order.292 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 293–294why, one step back293 set_key = key.lower().encode(self.encoding)294 set_value = value.encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 295–313why, one step back295296 found_indexes = []297 for idx, (item_key, item_value) in enumerate(self._list):298 if item_key == set_key:299 found_indexes.append(idx)300301 for idx in reversed(found_indexes[1:]):302 del self._list[idx]303304 if found_indexes:305 idx = found_indexes[0]306 self._list[idx] = (set_key, set_value)307 else:308 self._list.append((set_key, set_value))309310 def __delitem__(self, key: str) -> None:311 """312 Remove the header `key`.313 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 314why, one step back314 del_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 315–324why, one step back315316 pop_indexes = []317 for idx, (item_key, item_value) in enumerate(self._list):318 if item_key == del_key:319 pop_indexes.append(idx)320321 for idx in reversed(pop_indexes):322 del self._list[idx]323324 def __contains__(self, key: typing.Any) -> bool:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 325why, one step back325 get_header_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 326–343why, one step back326 for header_key, header_value in self._list:327 if header_key == get_header_key:328 return True329 return False330331 def __iter__(self) -> typing.Iterator[typing.Any]:332 return iter(self.keys())333334 def __len__(self) -> int:335 return len(self._list)336337 def __eq__(self, other: typing.Any) -> bool:338 if not isinstance(other, Headers):339 return False340 return sorted(self._list) == sorted(other._list)341342 def __repr__(self) -> str:343 class_name = self.__class__.__name__Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 344–348why, one step back344345 encoding_str = ""346 if self.encoding != "ascii":347 encoding_str = f", encoding={self.encoding!r}"348Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 349–350why, one step back349 as_dict = dict(self.items())350 if len(as_dict) == len(self):Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 351–353why, one step back351 return f"{class_name}({as_dict!r}{encoding_str})"352 as_list = self.items()353 return f"{class_name}({as_list!r}{encoding_str})"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 354–362why, one step back354355356class Request:357 def __init__(358 self,359 method: str,360 url: typing.Union[str, URL],361 *,362 headers: HeaderTypes = None,Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 363why, one step back363 content: ByteOrByteStream = b"",Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 364–366why, one step back364 ):365 self.method = method.upper()366 self.url = URL(url) if isinstance(url, str) else urlPrefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 367why, one step back367 if isinstance(content, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 368why, one step back368 self.is_streaming = FalsePrefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 369why, one step back369 self.content = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 370–371why, one step back370 else:371 self.is_streaming = TruePrefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 372why, one step back372 self.content_aiter = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 373–378why, one step back373 self.headers = Headers(headers)374375 async def read(self) -> bytes:376 """377 Read and return the response content.378 """Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 379–380why, one step back379 if not hasattr(self, "content"):380 content = b""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 381why, one step back381 async for part in self.stream():Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 382–384why, one step back382 content += part383 self.content = content384 return self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 385–387why, one step back385386 async def stream(self) -> typing.AsyncIterator[bytes]:387 if self.is_streaming:Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 388why, one step back388 async for part in self.content_aiter:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 389why, one step back389 yield partPrefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 390–391why, one step back390 elif self.content:391 yield self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 392–393why, one step back392393 def prepare(self) -> None:Response.contentTom Christiebefore adoption4c55113
lines 394–400why, one step back394 """395 Adds in any default headers. When using the `Client`, this will396 end up being called into by the `prepare_request()` stage.397398 You can omit this behavior by calling `Client.send()` with an399 explicitly built `Request` instance.400 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 401–408why, one step back401 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]402403 has_host = "host" in self.headers404 has_content_length = (405 "content-length" in self.headers or "transfer-encoding" in self.headers406 )407 has_accept_encoding = "accept-encoding" in self.headers408Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 409–410why, one step back409 if not has_host and self.url.authority:410 auto_headers.append((b"host", self.url.authority.encode("ascii")))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 411–413why, one step back411 if not has_content_length:412 if self.is_streaming:413 auto_headers.append((b"transfer-encoding", b"chunked"))Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 414–415why, one step back414 elif self.content:415 content_length = str(len(self.content)).encode()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 416–422why, one step back416 auto_headers.append((b"content-length", content_length))417 if not has_accept_encoding:418 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))419420 for item in reversed(auto_headers):421 self.headers.raw.insert(0, item)422Still truckin' onTom Christiebefore adoption6cb5c0d
lines 423–426why, one step back423 def __repr__(self) -> str:424 class_name = self.__class__.__name__425 url = str(self.url)426 return f"<{class_name}({self.method}, {url})>"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 427why, one step back427Still truckin' onTom Christiebefore adoption6cb5c0d
line 428why, one step back428Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 429–433why, one step back429class Response:430 def __init__(431 self,432 status_code: int,433 *,Finessing interfaceTom Christiebefore adoptiond7619a9
lines 434–436why, one step back434 reason_phrase: str = None,435 protocol: str = None,436 headers: HeaderTypes = None,Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 437why, one step back437 content: ByteOrByteStream = b"",Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 438–441why, one step back438 on_close: typing.Callable = None,439 request: Request = None,440 history: typing.List["Response"] = None,441 ):Truckin' onTom Christiebefore adoption6b60d95
lines 442–443why, one step back442 try:443 # Use a StatusCode IntEnum if possible, for a nicer representation.Still truckin' onTom Christiebefore adoption6cb5c0d
line 444why, one step back444 self.status_code = codes(status_code) # type: intTruckin' onTom Christiebefore adoption6b60d95
lines 445–446why, one step back445 except ValueError:446 self.status_code = status_codeResponse.contentTom Christiebefore adoption4c55113
line 447why, one step back447 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 448–450why, one step back448 self.protocol = protocol449 self.headers = Headers(headers)450Response.contentTom Christiebefore adoption4c55113
line 451why, one step back451 if isinstance(content, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 452why, one step back452 self.is_closed = TrueResponse.contentTom Christiebefore adoption4c55113
lines 453–454why, one step back453 self.is_stream_consumed = True454 self._raw_content = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 455why, one step back455 else:Response.contentTom Christiebefore adoption4c55113
lines 456–458why, one step back456 self.is_closed = False457 self.is_stream_consumed = False458 self._raw_stream = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 459why, one step back459Response.contentTom Christiebefore adoption4c55113
line 460why, one step back460 self.on_close = on_closeMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 461–462why, one step back461 self.request = request462 self.history = [] if history is None else list(history)response.next()Tom Christiebefore adoptiond652479
line 463why, one step back463 self.next = None # typing.Optional[typing.Callable]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 464–466why, one step back464465 @property466 def url(self) -> typing.Optional[URL]:Clean up response interfaceTom Christiebefore adoption4d908d0
lines 467–471why, one step back467 """468 Returns the URL for which the request was made.469470 Requires that `request` was provided when instantiating the response.471 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 472why, one step back472 return None if self.request is None else self.request.urlClean up response interfaceTom Christiebefore adoption4d908d0
lines 473–474why, one step back473474 @propertyResponse.contentTom Christiebefore adoption4c55113
lines 475–477why, one step back475 def content(self) -> bytes:476 if not hasattr(self, "_content"):477 if hasattr(self, "_raw_content"):Add response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 478–480why, one step back478 content = self.decoder.decode(self._raw_content)479 content += self.decoder.flush()480 self._content = contentResponse.contentTom Christiebefore adoption4c55113
lines 481–483why, one step back481 else:482 raise ResponseNotRead()483 return self._contentAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 484–519why, one step back484485 @property486 def text(self) -> str:487 if not hasattr(self, "_text"):488 content = self.content489 if not content:490 self._text = ""491 else:492 encoding = self.encoding493 self._text = content.decode(encoding, errors="replace")494 return self._text495496 @property497 def encoding(self) -> str:498 if not hasattr(self, "_encoding"):499 encoding = self.charset_encoding500 if encoding is None or not is_known_encoding(encoding):501 encoding = self.apparent_encoding502 if encoding is None or not is_known_encoding(encoding):503 encoding = "utf-8"504 self._encoding = encoding505 return self._encoding506507 @encoding.setter508 def encoding(self, value: str) -> None:509 self._encoding = value510511 @property512 def charset_encoding(self) -> typing.Optional[str]:513 """514 Return the encoding, as specified by the Content-Type header.515 """516 content_type = self.headers.get("Content-Type")517 if content_type is None:518 return None519Truckin' onTom Christiebefore adoption0ca1c84
lines 520–524why, one step back520 parsed = cgi.parse_header(content_type)521 media_type, params = parsed[0], parsed[-1]522 if "charset" in params:523 return params["charset"].strip("'\"")524Media types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 525–527why, one step back525 # RFC 2616 specifies that 'iso-8859-1' should be used as the default526 # for 'text/*' media types, if no charset is provided.527 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1Truckin' onTom Christiebefore adoption0ca1c84
lines 528–531why, one step back528 if media_type.startswith("text/"):529 return "iso-8859-1"530531 return NoneAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 532–538why, one step back532533 @property534 def apparent_encoding(self) -> typing.Optional[str]:535 """536 Return the encoding, as it appears to autodetection.537 """538 return chardet.detect(self.content)["encoding"]Response.contentTom Christiebefore adoption4c55113
lines 539–540why, one step back539540 @propertyClean up response interfaceTom Christiebefore adoption4d908d0
lines 541–547why, one step back541 def decoder(self) -> Decoder:542 """543 Returns a decoder instance which can be used to decode the raw byte544 content, depending on the Content-Encoding used in the response.545 """546 if not hasattr(self, "_decoder"):547 decoders = [] # type: typing.List[Decoder]Response.contentTom Christiebefore adoption4c55113
line 548why, one step back548 values = self.headers.getlist("content-encoding", split_commas=True)Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 549–551why, one step back549 for value in values:550 value = value.strip().lower()551 decoder_cls = SUPPORTED_DECODERS[value]Clean up response interfaceTom Christiebefore adoption4d908d0
lines 552–561why, one step back552 decoders.append(decoder_cls())553554 if len(decoders) == 1:555 self._decoder = decoders[0]556 elif len(decoders) > 1:557 self._decoder = MultiDecoder(decoders)558 else:559 self._decoder = IdentityDecoder()560561 return self._decoderMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 562–566why, one step back562563 async def read(self) -> bytes:564 """565 Read and return the response content.566 """Response.contentTom Christiebefore adoption4c55113
lines 567–568why, one step back567 if not hasattr(self, "_content"):568 content = b""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 569why, one step back569 async for part in self.stream():Response.contentTom Christiebefore adoption4c55113
lines 570–572why, one step back570 content += part571 self._content = content572 return self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 573–578why, one step back573574 async def stream(self) -> typing.AsyncIterator[bytes]:575 """576 A byte-iterator over the decoded response content.577 This allows us to handle gzip, deflate, and brotli encoded responses.578 """Response.contentTom Christiebefore adoption4c55113
lines 579–580why, one step back579 if hasattr(self, "_content"):580 yield self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 581–589why, one step back581 else:582 async for chunk in self.raw():583 yield self.decoder.decode(chunk)584 yield self.decoder.flush()585586 async def raw(self) -> typing.AsyncIterator[bytes]:587 """588 A byte-iterator over the raw response content.589 """Response.contentTom Christiebefore adoption4c55113
lines 590–601why, one step back590 if hasattr(self, "_raw_content"):591 yield self._raw_content592 else:593 if self.is_stream_consumed:594 raise StreamConsumed()595 if self.is_closed:596 raise ResponseClosed()597598 self.is_stream_consumed = True599 async for part in self._raw_stream:600 yield part601 await self.close()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 602–615why, one step back602603 async def close(self) -> None:604 """605 Close the response and release the connection.606 Automatically called if the response body is read to completion.607 """608 if not self.is_closed:609 self.is_closed = True610 if self.on_close is not None:611 await self.on_close()612613 @property614 def is_redirect(self) -> bool:615 return (Finessing interfaceTom Christiebefore adoptiond7619a9
lines 616–624why, one step back616 self.status_code617 in (618 codes.moved_permanently,619 codes.found,620 codes.see_other,621 codes.temporary_redirect,622 codes.permanent_redirect,623 )624 and "location" in self.headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 625why, one step back625 )Still truckin' onTom Christiebefore adoption6cb5c0d
lines 626–629why, one step back626627 def __repr__(self) -> str:628 class_name = self.__class__.__name__629 return f"<{class_name}(status_code={self.status_code})>"