models.py
This file
Path
httpcore/models.py
742 lines · 23.0 KiB · Python
Last changed by
Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
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
line 2why, one step back2import typingMerge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 3why, one step back3from urllib.parse import parse_qsl, urlencodeMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 4why, one step back4Add response.text and response.encodingTom Christiebefore adoptiond8df61b
line 5why, one step back5import chardetAdd idna support. More tests.Tom Christiebefore adoptionb948798
line 6why, one step back6import idnaUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 7why, one step back7import rfc3986Add response.text and response.encodingTom Christiebefore adoptiond8df61b
line 8why, one step back8Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 9why, one step back9from .config import SSLConfig, TimeoutConfigReorganise structureTom Christiebefore adoption0c6f618
line 10why, one step back10from .constants import codesMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 11–17why, one step back11from .decoders import (12 ACCEPT_ENCODING,13 SUPPORTED_DECODERS,14 Decoder,15 IdentityDecoder,16 MultiDecoder,17)Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 18–24why, one step back18from .exceptions import (19 HttpError,20 InvalidURL,21 ResponseClosed,22 ResponseNotRead,23 StreamConsumed,24)Add response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 25–30why, one step back25from .utils import (26 get_reason_phrase,27 is_known_encoding,28 normalize_header_key,29 normalize_header_value,30)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 31why, one step back31Finessing interfaceTom Christiebefore adoptiond7619a9
line 32why, one step back32URLTypes = typing.Union["URL", str]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 33why, one step back33Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 34–40why, one step back34QueryParamTypes = typing.Union[35 "QueryParams",36 typing.Mapping[str, str],37 typing.List[typing.Tuple[typing.Any, typing.Any]],38 str,39]40Finessing interfaceTom Christiebefore adoptiond7619a9
lines 41–46why, one step back41HeaderTypes = typing.Union[42 "Headers",43 typing.Dict[typing.AnyStr, typing.AnyStr],44 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],45]46Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 47why, one step back47ByteOrByteStream = typing.Union[bytes, typing.AsyncIterator[bytes]]Finessing interfaceTom Christiebefore adoptiond7619a9
lines 48–49why, one step back4849Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 50why, one step back50class URL:Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 51–56why, one step back51 def __init__(52 self,53 url: URLTypes,54 allow_relative: bool = False,55 query_params: QueryParamTypes = None,56 ) -> None:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 57why, one step back57 if isinstance(url, rfc3986.uri.URIReference):Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 58why, one step back58 self.components = urlAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 59–60why, one step back59 elif isinstance(url, str):60 self.components = rfc3986.api.uri_reference(url)Finessing interfaceTom Christiebefore adoptiond7619a9
lines 61–63why, one step back61 else:62 self.components = url.components63Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 64–69why, one step back64 # Handle IDNA domain names.65 if self.components.authority:66 idna_authority = self.components.authority.encode("idna").decode("ascii")67 if idna_authority != self.components.authority:68 self.components = self.components.copy_with(authority=idna_authority)69Fix docstringsTom Christiebefore adoption8a227c1
line 70why, one step back70 # Normalize scheme and domain name.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 71–72why, one step back71 self.components = self.components.normalize()72Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 73–77why, one step back73 # Add any query parameters.74 if query_params:75 query_string = str(QueryParams(query_params))76 self.components = self.components.copy_with(query=query_string)77Add idna support. More tests.Tom Christiebefore adoptionb948798
line 78why, one step back78 # Enforce absolute URLs by default.Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 79–84why, one step back79 if not allow_relative:80 if not self.scheme:81 raise InvalidURL("No scheme included in URL.")82 if self.scheme not in ("http", "https"):83 raise InvalidURL('URL scheme must be "http" or "https".')84 if not self.host:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 85why, one step back85 raise InvalidURL("No host included in URL.")Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 86–88why, one step back8687 @property88 def scheme(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 89why, one step back89 return self.components.scheme or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 90–91why, one step back9091 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 92–93why, one step back92 def authority(self) -> str:93 return self.components.authority or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 94–95why, one step back9495 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 96–97why, one step back96 def host(self) -> str:97 return self.components.host or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 98–103why, one step back9899 @property100 def port(self) -> int:101 port = self.components.port102 if port is None:103 return {"https": 443, "http": 80}[self.scheme]Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 104why, one step back104 return int(port)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 105–106why, one step back105106 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 107–114why, one step back107 def path(self) -> str:108 return self.components.path or "/"109110 @property111 def query(self) -> str:112 return self.components.query or ""113114 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 115why, one step back115 def full_path(self) -> str:Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
lines 116–118why, one step back116 path = self.path117 if self.query:118 path += "?" + self.queryMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 119–121why, one step back119 return path120121 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 122–125why, one step back122 def fragment(self) -> str:123 return self.components.fragment or ""124125 @propertyCarefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 126why, one step back126 def is_ssl(self) -> bool:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 127–129why, one step back127 return self.components.scheme == "https"128129 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 130–139why, one step back130 def is_absolute_url(self) -> bool:131 """132 Return `True` for absolute URLs such as 'http://example.com/path',133 and `False` for relative URLs such as '/path'.134 """135 # We don't use rfc3986's `is_absolute` because it treats136 # URLs with a fragment portion as not absolute.137 # What we actually care about is if the URL provides138 # a scheme and hostname to which connections should be made.139 return self.components.scheme and self.components.hostUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 140–141why, one step back140141 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 142–145why, one step back142 def is_relative_url(self) -> bool:143 return not self.is_absolute_url144145 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 146–148why, one step back146 def origin(self) -> "Origin":147 return Origin(self)148Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 149–152why, one step back149 def copy_with(self, **kwargs: typing.Any) -> "URL":150 return URL(self.components.copy_with(**kwargs))151152 def resolve_with(self, base_url: URLTypes) -> "URL":Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 153–156why, one step back153 """154 Return an absolute URL, using base_url as the base.155 """156 # We drop any fragment portion, because RFC 3986 strictlyFix docstringsTom Christiebefore adoption8a227c1
line 157why, one step back157 # treats URLs with a fragment portion as not being absolute URLs.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 158–159why, one step back158 base_url = URL(base_url).copy_with(fragment=None)159 return URL(self.components.resolve_with(base_url.components))Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 160why, one step back160Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 161–167why, one step back161 def __hash__(self) -> int:162 return hash(str(self))163164 def __eq__(self, other: typing.Any) -> bool:165 return isinstance(other, URL) and str(self) == str(other)166167 def __str__(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 168why, one step back168 return self.components.unsplit()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 169–176why, one step back169170 def __repr__(self) -> str:171 class_name = self.__class__.__name__172 url_str = str(self)173 return f"{class_name}({url_str!r})"174175176class Origin:Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 177–180why, one step back177 """178 The URL scheme and authority information, as a comparable, hashable object.179 """180Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 181–182why, one step back181 def __init__(self, url: URLTypes) -> None:182 if not isinstance(url, URL):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 183why, one step back183 url = URL(url)Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 184why, one step back184 self.is_ssl = url.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 185why, one step back185 self.host = url.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 186–191why, one step back186 self.port = url.port187188 def __eq__(self, other: typing.Any) -> bool:189 return (190 isinstance(other, self.__class__)191 and self.is_ssl == other.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 192why, one step back192 and self.host == other.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 193–196why, one step back193 and self.port == other.port194 )195196 def __hash__(self) -> int:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 197why, one step back197 return hash((self.is_ssl, self.host, self.port))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 198–199why, one step back198199Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 200–264why, one step back200class QueryParams(typing.Mapping):201 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:202 assert len(args) < 2, "Too many arguments."203 assert not (args and kwargs), "Cannot mix named and unnamed arguments."204205 value = args[0] if args else kwargs206207 if isinstance(value, str):208 items = parse_qsl(value)209 elif isinstance(value, QueryParams):210 items = value.multi_items()211 elif isinstance(value, list):212 items = value213 else:214 items = value.items() # type: ignore215216 self._list = [(str(k), str(v)) for k, v in items]217 self._dict = {str(k): str(v) for k, v in items}218219 def getlist(self, key: typing.Any) -> typing.List[str]:220 return [item_value for item_key, item_value in self._list if item_key == key]221222 def keys(self) -> typing.KeysView:223 return self._dict.keys()224225 def values(self) -> typing.ValuesView:226 return self._dict.values()227228 def items(self) -> typing.ItemsView:229 return self._dict.items()230231 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:232 return list(self._list)233234 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:235 if key in self._dict:236 return self._dict[key]237 return default238239 def __getitem__(self, key: typing.Any) -> str:240 return self._dict[key]241242 def __contains__(self, key: typing.Any) -> bool:243 return key in self._dict244245 def __iter__(self) -> typing.Iterator[typing.Any]:246 return iter(self.keys())247248 def __len__(self) -> int:249 return len(self._dict)250251 def __eq__(self, other: typing.Any) -> bool:252 if not isinstance(other, self.__class__):253 return False254 return sorted(self._list) == sorted(other._list)255256 def __str__(self) -> str:257 return urlencode(self._list)258259 def __repr__(self) -> str:260 class_name = self.__class__.__name__261 query_string = str(self)262 return f"{class_name}({query_string!r})"263264Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 265–266why, one step back265class Headers(typing.MutableMapping[str, str]):266 """Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 267why, one step back267 HTTP headers, as a case-insensitive multi-dict.Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 268–269why, one step back268 """269Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 270why, one step back270 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 271–276why, one step back271 if headers is None:272 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]273 elif isinstance(headers, Headers):274 self._list = list(headers.raw)275 elif isinstance(headers, dict):276 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 277why, one step back277 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 278–281why, one step back278 for k, v in headers.items()279 ]280 else:281 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 282–283why, one step back282 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))283 for k, v in headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 284why, one step back284 ]Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 285why, one step back285 self._encoding = encodingMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 286–287why, one step back286287 @propertyRejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 288–289why, one step back288 def encoding(self) -> str:289 """Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 290–291why, one step back290 Header encoding is mandated as ascii, but we allow fallbacks to utf-8291 or iso-8859-1.Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 292–316why, one step back292 """293 if self._encoding is None:294 for encoding in ["ascii", "utf-8"]:295 for key, value in self.raw:296 try:297 key.decode(encoding)298 value.decode(encoding)299 except UnicodeDecodeError:300 break301 else:302 # The else block runs if 'break' did not occur, meaning303 # all values fitted the encoding.304 self._encoding = encoding305 break306 else:307 # The ISO-8859-1 encoding covers all 256 code points in a byte,308 # so will never raise decode errors.309 self._encoding = "iso-8859-1"310 return self._encoding311312 @encoding.setter313 def encoding(self, value: str) -> None:314 self._encoding = value315316 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 317why, one step back317 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 318–321why, one step back318 """319 Returns a list of the raw header items, as byte pairs.320 May be mutated in-place.321 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 322–324why, one step back322 return self._list323324 def keys(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 325why, one step back325 return [key.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 326–327why, one step back326327 def values(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 328why, one step back328 return [value.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 329–331why, one step back329330 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore331 return [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 332why, one step back332 (key.decode(self.encoding), value.decode(self.encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 333–341why, one step back333 for key, value in self._list334 ]335336 def get(self, key: str, default: typing.Any = None) -> typing.Any:337 try:338 return self[key]339 except KeyError:340 return default341Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 342why, one step back342 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 343–349why, one step back343 """344 Return multiple header values.345 """346 get_header_key = key.lower().encode(self.encoding)347348 values = [349 item_value.decode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 350–353why, one step back350 for item_key, item_value in self._list351 if item_key == get_header_key352 ]353Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 354–361why, one step back354 if not split_commas:355 return values356357 split_values = []358 for value in values:359 split_values.extend([item.strip() for item in value.split(",")])360 return split_values361Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 362why, one step back362 def __getitem__(self, key: str) -> str:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 363–371why, one step back363 """364 Return a single header value.365366 If there are multiple headers with the same key, then we concatenate367 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2368 """369 normalized_key = key.lower().encode(self.encoding)370371 items = []Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 372why, one step back372 for header_key, header_value in self._list:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 373–378why, one step back373 if header_key == normalized_key:374 items.append(header_value.decode(self.encoding))375376 if items:377 return ", ".join(items)378Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 379–385why, one step back379 raise KeyError(key)380381 def __setitem__(self, key: str, value: str) -> None:382 """383 Set the header `key` to `value`, removing any duplicate entries.384 Retains insertion order.385 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 386–387why, one step back386 set_key = key.lower().encode(self.encoding)387 set_value = value.encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 388–406why, one step back388389 found_indexes = []390 for idx, (item_key, item_value) in enumerate(self._list):391 if item_key == set_key:392 found_indexes.append(idx)393394 for idx in reversed(found_indexes[1:]):395 del self._list[idx]396397 if found_indexes:398 idx = found_indexes[0]399 self._list[idx] = (set_key, set_value)400 else:401 self._list.append((set_key, set_value))402403 def __delitem__(self, key: str) -> None:404 """405 Remove the header `key`.406 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 407why, one step back407 del_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 408–417why, one step back408409 pop_indexes = []410 for idx, (item_key, item_value) in enumerate(self._list):411 if item_key == del_key:412 pop_indexes.append(idx)413414 for idx in reversed(pop_indexes):415 del self._list[idx]416417 def __contains__(self, key: typing.Any) -> bool:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 418why, one step back418 get_header_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 419–436why, one step back419 for header_key, header_value in self._list:420 if header_key == get_header_key:421 return True422 return False423424 def __iter__(self) -> typing.Iterator[typing.Any]:425 return iter(self.keys())426427 def __len__(self) -> int:428 return len(self._list)429430 def __eq__(self, other: typing.Any) -> bool:431 if not isinstance(other, Headers):432 return False433 return sorted(self._list) == sorted(other._list)434435 def __repr__(self) -> str:436 class_name = self.__class__.__name__Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 437–441why, one step back437438 encoding_str = ""439 if self.encoding != "ascii":440 encoding_str = f", encoding={self.encoding!r}"441Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 442–443why, one step back442 as_dict = dict(self.items())443 if len(as_dict) == len(self):Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 444–446why, one step back444 return f"{class_name}({as_dict!r}{encoding_str})"445 as_list = self.items()446 return f"{class_name}({as_list!r}{encoding_str})"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 447–454why, one step back447448449class Request:450 def __init__(451 self,452 method: str,453 url: typing.Union[str, URL],454 *,Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 455why, one step back455 query_params: QueryParamTypes = None,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 456why, one step back456 headers: HeaderTypes = None,Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 457why, one step back457 content: ByteOrByteStream = b"",Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 458–459why, one step back458 ):459 self.method = method.upper()Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 460why, one step back460 self.url = URL(url, query_params=query_params)Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 461why, one step back461 if isinstance(content, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 462why, one step back462 self.is_streaming = FalsePrefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 463why, one step back463 self.content = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 464–465why, one step back464 else:465 self.is_streaming = TruePrefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 466why, one step back466 self.content_aiter = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 467–472why, one step back467 self.headers = Headers(headers)468469 async def read(self) -> bytes:470 """471 Read and return the response content.472 """Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 473–474why, one step back473 if not hasattr(self, "content"):474 content = b""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 475why, one step back475 async for part in self.stream():Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 476–478why, one step back476 content += part477 self.content = content478 return self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 479–481why, one step back479480 async def stream(self) -> typing.AsyncIterator[bytes]:481 if self.is_streaming:Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 482why, one step back482 async for part in self.content_aiter:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 483why, one step back483 yield partPrefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 484–485why, one step back484 elif self.content:485 yield self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 486–487why, one step back486487 def prepare(self) -> None:Response.contentTom Christiebefore adoption4c55113
lines 488–494why, one step back488 """489 Adds in any default headers. When using the `Client`, this will490 end up being called into by the `prepare_request()` stage.491492 You can omit this behavior by calling `Client.send()` with an493 explicitly built `Request` instance.494 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 495–502why, one step back495 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]496497 has_host = "host" in self.headers498 has_content_length = (499 "content-length" in self.headers or "transfer-encoding" in self.headers500 )501 has_accept_encoding = "accept-encoding" in self.headers502Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 503–504why, one step back503 if not has_host and self.url.authority:504 auto_headers.append((b"host", self.url.authority.encode("ascii")))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 505–507why, one step back505 if not has_content_length:506 if self.is_streaming:507 auto_headers.append((b"transfer-encoding", b"chunked"))Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 508–509why, one step back508 elif self.content:509 content_length = str(len(self.content)).encode()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 510–516why, one step back510 auto_headers.append((b"content-length", content_length))511 if not has_accept_encoding:512 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))513514 for item in reversed(auto_headers):515 self.headers.raw.insert(0, item)516Still truckin' onTom Christiebefore adoption6cb5c0d
lines 517–520why, one step back517 def __repr__(self) -> str:518 class_name = self.__class__.__name__519 url = str(self.url)520 return f"<{class_name}({self.method}, {url})>"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 521why, one step back521Still truckin' onTom Christiebefore adoption6cb5c0d
line 522why, one step back522Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 523–527why, one step back523class Response:524 def __init__(525 self,526 status_code: int,527 *,Finessing interfaceTom Christiebefore adoptiond7619a9
lines 528–530why, one step back528 reason_phrase: str = None,529 protocol: str = None,530 headers: HeaderTypes = None,Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 531why, one step back531 content: ByteOrByteStream = b"",Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 532–535why, one step back532 on_close: typing.Callable = None,533 request: Request = None,534 history: typing.List["Response"] = None,535 ):Truckin' onTom Christiebefore adoption6b60d95
lines 536–537why, one step back536 try:537 # Use a StatusCode IntEnum if possible, for a nicer representation.Still truckin' onTom Christiebefore adoption6cb5c0d
line 538why, one step back538 self.status_code = codes(status_code) # type: intTruckin' onTom Christiebefore adoption6b60d95
lines 539–540why, one step back539 except ValueError:540 self.status_code = status_codeResponse.contentTom Christiebefore adoption4c55113
line 541why, one step back541 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 542–544why, one step back542 self.protocol = protocol543 self.headers = Headers(headers)544Response.contentTom Christiebefore adoption4c55113
line 545why, one step back545 if isinstance(content, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 546why, one step back546 self.is_closed = TrueResponse.contentTom Christiebefore adoption4c55113
lines 547–548why, one step back547 self.is_stream_consumed = True548 self._raw_content = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 549why, one step back549 else:Response.contentTom Christiebefore adoption4c55113
lines 550–552why, one step back550 self.is_closed = False551 self.is_stream_consumed = False552 self._raw_stream = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 553why, one step back553Response.contentTom Christiebefore adoption4c55113
line 554why, one step back554 self.on_close = on_closeMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 555–556why, one step back555 self.request = request556 self.history = [] if history is None else list(history)response.next()Tom Christiebefore adoptiond652479
line 557why, one step back557 self.next = None # typing.Optional[typing.Callable]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 558–560why, one step back558559 @property560 def url(self) -> typing.Optional[URL]:Clean up response interfaceTom Christiebefore adoption4d908d0
lines 561–565why, one step back561 """562 Returns the URL for which the request was made.563564 Requires that `request` was provided when instantiating the response.565 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 566why, one step back566 return None if self.request is None else self.request.urlClean up response interfaceTom Christiebefore adoption4d908d0
lines 567–568why, one step back567568 @propertyResponse.contentTom Christiebefore adoption4c55113
lines 569–571why, one step back569 def content(self) -> bytes:570 if not hasattr(self, "_content"):571 if hasattr(self, "_raw_content"):Add response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 572–574why, one step back572 content = self.decoder.decode(self._raw_content)573 content += self.decoder.flush()574 self._content = contentResponse.contentTom Christiebefore adoption4c55113
lines 575–577why, one step back575 else:576 raise ResponseNotRead()577 return self._contentAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 578–613why, one step back578579 @property580 def text(self) -> str:581 if not hasattr(self, "_text"):582 content = self.content583 if not content:584 self._text = ""585 else:586 encoding = self.encoding587 self._text = content.decode(encoding, errors="replace")588 return self._text589590 @property591 def encoding(self) -> str:592 if not hasattr(self, "_encoding"):593 encoding = self.charset_encoding594 if encoding is None or not is_known_encoding(encoding):595 encoding = self.apparent_encoding596 if encoding is None or not is_known_encoding(encoding):597 encoding = "utf-8"598 self._encoding = encoding599 return self._encoding600601 @encoding.setter602 def encoding(self, value: str) -> None:603 self._encoding = value604605 @property606 def charset_encoding(self) -> typing.Optional[str]:607 """608 Return the encoding, as specified by the Content-Type header.609 """610 content_type = self.headers.get("Content-Type")611 if content_type is None:612 return None613Truckin' onTom Christiebefore adoption0ca1c84
lines 614–618why, one step back614 parsed = cgi.parse_header(content_type)615 media_type, params = parsed[0], parsed[-1]616 if "charset" in params:617 return params["charset"].strip("'\"")618Media types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 619–621why, one step back619 # RFC 2616 specifies that 'iso-8859-1' should be used as the default620 # for 'text/*' media types, if no charset is provided.621 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1Truckin' onTom Christiebefore adoption0ca1c84
lines 622–625why, one step back622 if media_type.startswith("text/"):623 return "iso-8859-1"624625 return NoneAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 626–632why, one step back626627 @property628 def apparent_encoding(self) -> typing.Optional[str]:629 """630 Return the encoding, as it appears to autodetection.631 """632 return chardet.detect(self.content)["encoding"]Response.contentTom Christiebefore adoption4c55113
lines 633–634why, one step back633634 @propertyClean up response interfaceTom Christiebefore adoption4d908d0
lines 635–641why, one step back635 def decoder(self) -> Decoder:636 """637 Returns a decoder instance which can be used to decode the raw byte638 content, depending on the Content-Encoding used in the response.639 """640 if not hasattr(self, "_decoder"):641 decoders = [] # type: typing.List[Decoder]Response.contentTom Christiebefore adoption4c55113
line 642why, one step back642 values = self.headers.getlist("content-encoding", split_commas=True)Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 643–645why, one step back643 for value in values:644 value = value.strip().lower()645 decoder_cls = SUPPORTED_DECODERS[value]Clean up response interfaceTom Christiebefore adoption4d908d0
lines 646–655why, one step back646 decoders.append(decoder_cls())647648 if len(decoders) == 1:649 self._decoder = decoders[0]650 elif len(decoders) > 1:651 self._decoder = MultiDecoder(decoders)652 else:653 self._decoder = IdentityDecoder()654655 return self._decoderMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 656–660why, one step back656657 async def read(self) -> bytes:658 """659 Read and return the response content.660 """Response.contentTom Christiebefore adoption4c55113
lines 661–662why, one step back661 if not hasattr(self, "_content"):662 content = b""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 663why, one step back663 async for part in self.stream():Response.contentTom Christiebefore adoption4c55113
lines 664–666why, one step back664 content += part665 self._content = content666 return self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 667–672why, one step back667668 async def stream(self) -> typing.AsyncIterator[bytes]:669 """670 A byte-iterator over the decoded response content.671 This allows us to handle gzip, deflate, and brotli encoded responses.672 """Response.contentTom Christiebefore adoption4c55113
lines 673–674why, one step back673 if hasattr(self, "_content"):674 yield self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 675–683why, one step back675 else:676 async for chunk in self.raw():677 yield self.decoder.decode(chunk)678 yield self.decoder.flush()679680 async def raw(self) -> typing.AsyncIterator[bytes]:681 """682 A byte-iterator over the raw response content.683 """Response.contentTom Christiebefore adoption4c55113
lines 684–695why, one step back684 if hasattr(self, "_raw_content"):685 yield self._raw_content686 else:687 if self.is_stream_consumed:688 raise StreamConsumed()689 if self.is_closed:690 raise ResponseClosed()691692 self.is_stream_consumed = True693 async for part in self._raw_stream:694 yield part695 await self.close()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 696–709why, one step back696697 async def close(self) -> None:698 """699 Close the response and release the connection.700 Automatically called if the response body is read to completion.701 """702 if not self.is_closed:703 self.is_closed = True704 if self.on_close is not None:705 await self.on_close()706707 @property708 def is_redirect(self) -> bool:709 return (Finessing interfaceTom Christiebefore adoptiond7619a9
lines 710–718why, one step back710 self.status_code711 in (712 codes.moved_permanently,713 codes.found,714 codes.see_other,715 codes.temporary_redirect,716 codes.permanent_redirect,717 )718 and "location" in self.headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 719why, one step back719 )Still truckin' onTom Christiebefore adoption6cb5c0d
lines 720–723why, one step back720721 def __repr__(self) -> str:722 class_name = self.__class__.__name__723 return f"<{class_name}(status_code={self.status_code})>"Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 724–742why, one step back724725 def raise_for_status(self) -> None:726 """727 Raise the `HttpError` if one occurred.728 """729 message = (730 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"731 "For more information check: https://httpstatuses.com/{0.status_code}"732 )733734 if 400 <= self.status_code < 500:735 message = message.format(self, error_type="Client Error")736 elif 500 <= self.status_code < 600:737 message = message.format(self, error_type="Server Error")738 else:739 message = ""740741 if message:742 raise HttpError(message)