models.py
This file
Path
httpcore/models.py
826 lines · 25.3 KiB · Python
Last changed by
repr change: <SyncResponse ...> -> <Response ...>Tom Christiebefore adoption73d5fca
History of this fileTake it
Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 1why, one step back1import asyncioAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
line 2why, one step back2import cgiMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 3why, one step back3import typingMerge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 4why, one step back4from urllib.parse import parse_qsl, urlencodeMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 5why, one step back5Add response.text and response.encodingTom Christiebefore adoptiond8df61b
line 6why, one step back6import chardetAdd idna support. More tests.Tom Christiebefore adoptionb948798
line 7why, one step back7import idnaUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 8why, one step back8import rfc3986Add response.text and response.encodingTom Christiebefore adoptiond8df61b
line 9why, one step back9Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 10–17why, one step back10from .config import SSLConfig, TimeoutConfig11from .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)Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369
line 25why, one step back25from .status_codes import codesAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 26–31why, one step back26from .utils import (27 get_reason_phrase,28 is_known_encoding,29 normalize_header_key,30 normalize_header_value,31)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 32why, one step back32Finessing interfaceTom Christiebefore adoptiond7619a9
line 33why, one step back33URLTypes = typing.Union["URL", str]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 34why, one step back34Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 35–41why, one step back35QueryParamTypes = typing.Union[36 "QueryParams",37 typing.Mapping[str, str],38 typing.List[typing.Tuple[typing.Any, typing.Any]],39 str,40]41Finessing interfaceTom Christiebefore adoptiond7619a9
lines 42–47why, one step back42HeaderTypes = typing.Union[43 "Headers",44 typing.Dict[typing.AnyStr, typing.AnyStr],45 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],46]47Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 48why, one step back48RequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]Finessing interfaceTom Christiebefore adoptiond7619a9
line 49why, one step back49Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 50why, one step back50ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]Finessing interfaceTom Christiebefore adoptiond7619a9
line 51why, one step back51Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 52why, one step back52Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 53why, one step back53class URL:Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 54–59why, one step back54 def __init__(55 self,56 url: URLTypes,57 allow_relative: bool = False,58 query_params: QueryParamTypes = None,59 ) -> None:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 60why, one step back60 if isinstance(url, rfc3986.uri.URIReference):Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 61why, one step back61 self.components = urlAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 62–63why, one step back62 elif isinstance(url, str):63 self.components = rfc3986.api.uri_reference(url)Finessing interfaceTom Christiebefore adoptiond7619a9
lines 64–66why, one step back64 else:65 self.components = url.components66Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 67–72why, one step back67 # Handle IDNA domain names.68 if self.components.authority:69 idna_authority = self.components.authority.encode("idna").decode("ascii")70 if idna_authority != self.components.authority:71 self.components = self.components.copy_with(authority=idna_authority)72Fix docstringsTom Christiebefore adoption8a227c1
line 73why, one step back73 # Normalize scheme and domain name.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 74–75why, one step back74 self.components = self.components.normalize()75Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 76–80why, one step back76 # Add any query parameters.77 if query_params:78 query_string = str(QueryParams(query_params))79 self.components = self.components.copy_with(query=query_string)80Add idna support. More tests.Tom Christiebefore adoptionb948798
line 81why, one step back81 # Enforce absolute URLs by default.Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 82–87why, one step back82 if not allow_relative:83 if not self.scheme:84 raise InvalidURL("No scheme included in URL.")85 if self.scheme not in ("http", "https"):86 raise InvalidURL('URL scheme must be "http" or "https".')87 if not self.host:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 88why, one step back88 raise InvalidURL("No host included in URL.")Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 89–91why, one step back8990 @property91 def scheme(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 92why, one step back92 return self.components.scheme or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 93–94why, one step back9394 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 95–96why, one step back95 def authority(self) -> str:96 return self.components.authority or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 97–98why, one step back9798 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 99–100why, one step back99 def host(self) -> str:100 return self.components.host or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 101–106why, one step back101102 @property103 def port(self) -> int:104 port = self.components.port105 if port is None:106 return {"https": 443, "http": 80}[self.scheme]Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 107why, one step back107 return int(port)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 108–109why, one step back108109 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 110–117why, one step back110 def path(self) -> str:111 return self.components.path or "/"112113 @property114 def query(self) -> str:115 return self.components.query or ""116117 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 118why, one step back118 def full_path(self) -> str:Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
lines 119–121why, one step back119 path = self.path120 if self.query:121 path += "?" + self.queryMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 122–124why, one step back122 return path123124 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 125–128why, one step back125 def fragment(self) -> str:126 return self.components.fragment or ""127128 @propertyCarefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 129why, one step back129 def is_ssl(self) -> bool:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 130–132why, one step back130 return self.components.scheme == "https"131132 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 133–142why, one step back133 def is_absolute_url(self) -> bool:134 """135 Return `True` for absolute URLs such as 'http://example.com/path',136 and `False` for relative URLs such as '/path'.137 """138 # We don't use rfc3986's `is_absolute` because it treats139 # URLs with a fragment portion as not absolute.140 # What we actually care about is if the URL provides141 # a scheme and hostname to which connections should be made.142 return self.components.scheme and self.components.hostUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 143–144why, one step back143144 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 145–148why, one step back145 def is_relative_url(self) -> bool:146 return not self.is_absolute_url147148 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 149–151why, one step back149 def origin(self) -> "Origin":150 return Origin(self)151Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 152–155why, one step back152 def copy_with(self, **kwargs: typing.Any) -> "URL":153 return URL(self.components.copy_with(**kwargs))154155 def resolve_with(self, base_url: URLTypes) -> "URL":Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 156–159why, one step back156 """157 Return an absolute URL, using base_url as the base.158 """159 # We drop any fragment portion, because RFC 3986 strictlyFix docstringsTom Christiebefore adoption8a227c1
line 160why, one step back160 # treats URLs with a fragment portion as not being absolute URLs.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 161–162why, one step back161 base_url = URL(base_url).copy_with(fragment=None)162 return URL(self.components.resolve_with(base_url.components))Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 163why, one step back163Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 164–170why, one step back164 def __hash__(self) -> int:165 return hash(str(self))166167 def __eq__(self, other: typing.Any) -> bool:168 return isinstance(other, URL) and str(self) == str(other)169170 def __str__(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 171why, one step back171 return self.components.unsplit()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 172–179why, one step back172173 def __repr__(self) -> str:174 class_name = self.__class__.__name__175 url_str = str(self)176 return f"{class_name}({url_str!r})"177178179class Origin:Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 180–183why, one step back180 """181 The URL scheme and authority information, as a comparable, hashable object.182 """183Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 184–185why, one step back184 def __init__(self, url: URLTypes) -> None:185 if not isinstance(url, URL):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 186why, one step back186 url = URL(url)Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 187why, one step back187 self.is_ssl = url.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 188why, one step back188 self.host = url.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 189–194why, one step back189 self.port = url.port190191 def __eq__(self, other: typing.Any) -> bool:192 return (193 isinstance(other, self.__class__)194 and self.is_ssl == other.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 195why, one step back195 and self.host == other.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 196–199why, one step back196 and self.port == other.port197 )198199 def __hash__(self) -> int:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 200why, one step back200 return hash((self.is_ssl, self.host, self.port))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 201–202why, one step back201202Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 203why, one step back203class QueryParams(typing.Mapping[str, str]):Improve class __repr__Tom Christiebefore adoption666d5a8
lines 204–207why, one step back204 """205 URL query parameters, as a multi-dict.206 """207Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 208–271why, one step back208 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:209 assert len(args) < 2, "Too many arguments."210 assert not (args and kwargs), "Cannot mix named and unnamed arguments."211212 value = args[0] if args else kwargs213214 if isinstance(value, str):215 items = parse_qsl(value)216 elif isinstance(value, QueryParams):217 items = value.multi_items()218 elif isinstance(value, list):219 items = value220 else:221 items = value.items() # type: ignore222223 self._list = [(str(k), str(v)) for k, v in items]224 self._dict = {str(k): str(v) for k, v in items}225226 def getlist(self, key: typing.Any) -> typing.List[str]:227 return [item_value for item_key, item_value in self._list if item_key == key]228229 def keys(self) -> typing.KeysView:230 return self._dict.keys()231232 def values(self) -> typing.ValuesView:233 return self._dict.values()234235 def items(self) -> typing.ItemsView:236 return self._dict.items()237238 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:239 return list(self._list)240241 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:242 if key in self._dict:243 return self._dict[key]244 return default245246 def __getitem__(self, key: typing.Any) -> str:247 return self._dict[key]248249 def __contains__(self, key: typing.Any) -> bool:250 return key in self._dict251252 def __iter__(self) -> typing.Iterator[typing.Any]:253 return iter(self.keys())254255 def __len__(self) -> int:256 return len(self._dict)257258 def __eq__(self, other: typing.Any) -> bool:259 if not isinstance(other, self.__class__):260 return False261 return sorted(self._list) == sorted(other._list)262263 def __str__(self) -> str:264 return urlencode(self._list)265266 def __repr__(self) -> str:267 class_name = self.__class__.__name__268 query_string = str(self)269 return f"{class_name}({query_string!r})"270271Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 272–273why, one step back272class Headers(typing.MutableMapping[str, str]):273 """Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 274why, one step back274 HTTP headers, as a case-insensitive multi-dict.Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 275–276why, one step back275 """276Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 277why, one step back277 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 278–283why, one step back278 if headers is None:279 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]280 elif isinstance(headers, Headers):281 self._list = list(headers.raw)282 elif isinstance(headers, dict):283 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 284why, one step back284 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 285–288why, one step back285 for k, v in headers.items()286 ]287 else:288 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 289–290why, one step back289 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))290 for k, v in headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 291why, one step back291 ]Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 292why, one step back292 self._encoding = encodingMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 293–294why, one step back293294 @propertyRejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 295–296why, one step back295 def encoding(self) -> str:296 """Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 297–298why, one step back297 Header encoding is mandated as ascii, but we allow fallbacks to utf-8298 or iso-8859-1.Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 299–323why, one step back299 """300 if self._encoding is None:301 for encoding in ["ascii", "utf-8"]:302 for key, value in self.raw:303 try:304 key.decode(encoding)305 value.decode(encoding)306 except UnicodeDecodeError:307 break308 else:309 # The else block runs if 'break' did not occur, meaning310 # all values fitted the encoding.311 self._encoding = encoding312 break313 else:314 # The ISO-8859-1 encoding covers all 256 code points in a byte,315 # so will never raise decode errors.316 self._encoding = "iso-8859-1"317 return self._encoding318319 @encoding.setter320 def encoding(self, value: str) -> None:321 self._encoding = value322323 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 324why, one step back324 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 325–328why, one step back325 """326 Returns a list of the raw header items, as byte pairs.327 May be mutated in-place.328 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 329–331why, one step back329 return self._list330331 def keys(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 332why, one step back332 return [key.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 333–334why, one step back333334 def values(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 335why, one step back335 return [value.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 336–338why, one step back336337 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore338 return [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 339why, one step back339 (key.decode(self.encoding), value.decode(self.encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 340–348why, one step back340 for key, value in self._list341 ]342343 def get(self, key: str, default: typing.Any = None) -> typing.Any:344 try:345 return self[key]346 except KeyError:347 return default348Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 349why, one step back349 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 350–356why, one step back350 """351 Return multiple header values.352 """353 get_header_key = key.lower().encode(self.encoding)354355 values = [356 item_value.decode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 357–360why, one step back357 for item_key, item_value in self._list358 if item_key == get_header_key359 ]360Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 361–368why, one step back361 if not split_commas:362 return values363364 split_values = []365 for value in values:366 split_values.extend([item.strip() for item in value.split(",")])367 return split_values368Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 369why, one step back369 def __getitem__(self, key: str) -> str:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 370–378why, one step back370 """371 Return a single header value.372373 If there are multiple headers with the same key, then we concatenate374 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2375 """376 normalized_key = key.lower().encode(self.encoding)377378 items = []Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 379why, one step back379 for header_key, header_value in self._list:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 380–385why, one step back380 if header_key == normalized_key:381 items.append(header_value.decode(self.encoding))382383 if items:384 return ", ".join(items)385Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 386–392why, one step back386 raise KeyError(key)387388 def __setitem__(self, key: str, value: str) -> None:389 """390 Set the header `key` to `value`, removing any duplicate entries.391 Retains insertion order.392 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 393–394why, one step back393 set_key = key.lower().encode(self.encoding)394 set_value = value.encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 395–413why, one step back395396 found_indexes = []397 for idx, (item_key, item_value) in enumerate(self._list):398 if item_key == set_key:399 found_indexes.append(idx)400401 for idx in reversed(found_indexes[1:]):402 del self._list[idx]403404 if found_indexes:405 idx = found_indexes[0]406 self._list[idx] = (set_key, set_value)407 else:408 self._list.append((set_key, set_value))409410 def __delitem__(self, key: str) -> None:411 """412 Remove the header `key`.413 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 414why, one step back414 del_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 415–424why, one step back415416 pop_indexes = []417 for idx, (item_key, item_value) in enumerate(self._list):418 if item_key == del_key:419 pop_indexes.append(idx)420421 for idx in reversed(pop_indexes):422 del self._list[idx]423424 def __contains__(self, key: typing.Any) -> bool:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 425why, one step back425 get_header_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 426–443why, one step back426 for header_key, header_value in self._list:427 if header_key == get_header_key:428 return True429 return False430431 def __iter__(self) -> typing.Iterator[typing.Any]:432 return iter(self.keys())433434 def __len__(self) -> int:435 return len(self._list)436437 def __eq__(self, other: typing.Any) -> bool:438 if not isinstance(other, Headers):439 return False440 return sorted(self._list) == sorted(other._list)441442 def __repr__(self) -> str:443 class_name = self.__class__.__name__Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 444–448why, one step back444445 encoding_str = ""446 if self.encoding != "ascii":447 encoding_str = f", encoding={self.encoding!r}"448Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 449–450why, one step back449 as_dict = dict(self.items())450 if len(as_dict) == len(self):Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 451–453why, one step back451 return f"{class_name}({as_dict!r}{encoding_str})"452 as_list = self.items()453 return f"{class_name}({as_list!r}{encoding_str})"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 454–461why, one step back454455456class Request:457 def __init__(458 self,459 method: str,460 url: typing.Union[str, URL],461 *,Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 462why, one step back462 data: RequestData = b"",Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 463why, one step back463 query_params: QueryParamTypes = None,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 464–466why, one step back464 headers: HeaderTypes = None,465 ):466 self.method = method.upper()Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 467why, one step back467 self.url = URL(url, query_params=query_params)Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
lines 468–470why, one step back468 self.headers = Headers(headers)469470 if isinstance(data, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 471why, one step back471 self.is_streaming = FalseMerge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
lines 472–476why, one step back472 self.content = data473 elif isinstance(data, dict):474 self.is_streaming = False475 self.content = urlencode(data, doseq=True).encode("utf-8")476 self.headers["Content-Type"] = "application/x-www-form-urlencoded"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 477–478why, one step back477 else:478 self.is_streaming = TrueMerge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 479why, one step back479 self.content_aiter = dataMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 480–484why, one step back480481 async def read(self) -> bytes:482 """483 Read and return the response content.484 """Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 485why, one step back485 if not hasattr(self, "content"):Merge pull request #53 from yunstanford/patch-0Tom Christiebefore adoption21ac95a
line 486why, one step back486 self.content = b"".join([part async for part in self.stream()])Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 487why, one step back487 return self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 488–490why, one step back488489 async def stream(self) -> typing.AsyncIterator[bytes]:490 if self.is_streaming:Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 491why, one step back491 async for part in self.content_aiter:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 492why, one step back492 yield partPrefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 493–494why, one step back493 elif self.content:494 yield self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 495–496why, one step back495496 def prepare(self) -> None:Response.contentTom Christiebefore adoption4c55113
lines 497–503why, one step back497 """498 Adds in any default headers. When using the `Client`, this will499 end up being called into by the `prepare_request()` stage.500501 You can omit this behavior by calling `Client.send()` with an502 explicitly built `Request` instance.503 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 504–511why, one step back504 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]505506 has_host = "host" in self.headers507 has_content_length = (508 "content-length" in self.headers or "transfer-encoding" in self.headers509 )510 has_accept_encoding = "accept-encoding" in self.headers511Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 512–513why, one step back512 if not has_host and self.url.authority:513 auto_headers.append((b"host", self.url.authority.encode("ascii")))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 514–516why, one step back514 if not has_content_length:515 if self.is_streaming:516 auto_headers.append((b"transfer-encoding", b"chunked"))Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 517–518why, one step back517 elif self.content:518 content_length = str(len(self.content)).encode()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 519–525why, one step back519 auto_headers.append((b"content-length", content_length))520 if not has_accept_encoding:521 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))522523 for item in reversed(auto_headers):524 self.headers.raw.insert(0, item)525Still truckin' onTom Christiebefore adoption6cb5c0d
lines 526–528why, one step back526 def __repr__(self) -> str:527 class_name = self.__class__.__name__528 url = str(self.url)Improve class __repr__Tom Christiebefore adoption666d5a8
line 529why, one step back529 return f"<{class_name}({self.method!r}, {url!r})>"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 530why, one step back530Still truckin' onTom Christiebefore adoption6cb5c0d
line 531why, one step back531Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 532–536why, one step back532class Response:533 def __init__(534 self,535 status_code: int,536 *,Finessing interfaceTom Christiebefore adoptiond7619a9
lines 537–539why, one step back537 reason_phrase: str = None,538 protocol: str = None,539 headers: HeaderTypes = None,Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 540why, one step back540 content: ResponseContent = b"",Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 541–544why, one step back541 on_close: typing.Callable = None,542 request: Request = None,543 history: typing.List["Response"] = None,544 ):Truckin' onTom Christiebefore adoption6b60d95
lines 545–546why, one step back545 try:546 # Use a StatusCode IntEnum if possible, for a nicer representation.Still truckin' onTom Christiebefore adoption6cb5c0d
line 547why, one step back547 self.status_code = codes(status_code) # type: intTruckin' onTom Christiebefore adoption6b60d95
lines 548–549why, one step back548 except ValueError:549 self.status_code = status_codeResponse.contentTom Christiebefore adoption4c55113
line 550why, one step back550 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 551–553why, one step back551 self.protocol = protocol552 self.headers = Headers(headers)553Response.contentTom Christiebefore adoption4c55113
line 554why, one step back554 if isinstance(content, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 555why, one step back555 self.is_closed = TrueResponse.contentTom Christiebefore adoption4c55113
lines 556–557why, one step back556 self.is_stream_consumed = True557 self._raw_content = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 558why, one step back558 else:Response.contentTom Christiebefore adoption4c55113
lines 559–561why, one step back559 self.is_closed = False560 self.is_stream_consumed = False561 self._raw_stream = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 562why, one step back562Response.contentTom Christiebefore adoption4c55113
line 563why, one step back563 self.on_close = on_closeMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 564–565why, one step back564 self.request = request565 self.history = [] if history is None else list(history)response.next()Tom Christiebefore adoptiond652479
line 566why, one step back566 self.next = None # typing.Optional[typing.Callable]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 567–569why, one step back567568 @property569 def url(self) -> typing.Optional[URL]:Clean up response interfaceTom Christiebefore adoption4d908d0
lines 570–574why, one step back570 """571 Returns the URL for which the request was made.572573 Requires that `request` was provided when instantiating the response.574 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 575why, one step back575 return None if self.request is None else self.request.urlClean up response interfaceTom Christiebefore adoption4d908d0
lines 576–577why, one step back576577 @propertyResponse.contentTom Christiebefore adoption4c55113
lines 578–580why, one step back578 def content(self) -> bytes:579 if not hasattr(self, "_content"):580 if hasattr(self, "_raw_content"):Add response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 581–583why, one step back581 content = self.decoder.decode(self._raw_content)582 content += self.decoder.flush()583 self._content = contentResponse.contentTom Christiebefore adoption4c55113
lines 584–586why, one step back584 else:585 raise ResponseNotRead()586 return self._contentAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 587–622why, one step back587588 @property589 def text(self) -> str:590 if not hasattr(self, "_text"):591 content = self.content592 if not content:593 self._text = ""594 else:595 encoding = self.encoding596 self._text = content.decode(encoding, errors="replace")597 return self._text598599 @property600 def encoding(self) -> str:601 if not hasattr(self, "_encoding"):602 encoding = self.charset_encoding603 if encoding is None or not is_known_encoding(encoding):604 encoding = self.apparent_encoding605 if encoding is None or not is_known_encoding(encoding):606 encoding = "utf-8"607 self._encoding = encoding608 return self._encoding609610 @encoding.setter611 def encoding(self, value: str) -> None:612 self._encoding = value613614 @property615 def charset_encoding(self) -> typing.Optional[str]:616 """617 Return the encoding, as specified by the Content-Type header.618 """619 content_type = self.headers.get("Content-Type")620 if content_type is None:621 return None622Truckin' onTom Christiebefore adoption0ca1c84
lines 623–627why, one step back623 parsed = cgi.parse_header(content_type)624 media_type, params = parsed[0], parsed[-1]625 if "charset" in params:626 return params["charset"].strip("'\"")627Media types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 628–630why, one step back628 # RFC 2616 specifies that 'iso-8859-1' should be used as the default629 # for 'text/*' media types, if no charset is provided.630 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1Truckin' onTom Christiebefore adoption0ca1c84
lines 631–634why, one step back631 if media_type.startswith("text/"):632 return "iso-8859-1"633634 return NoneAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 635–641why, one step back635636 @property637 def apparent_encoding(self) -> typing.Optional[str]:638 """639 Return the encoding, as it appears to autodetection.640 """641 return chardet.detect(self.content)["encoding"]Response.contentTom Christiebefore adoption4c55113
lines 642–643why, one step back642643 @propertyClean up response interfaceTom Christiebefore adoption4d908d0
lines 644–650why, one step back644 def decoder(self) -> Decoder:645 """646 Returns a decoder instance which can be used to decode the raw byte647 content, depending on the Content-Encoding used in the response.648 """649 if not hasattr(self, "_decoder"):650 decoders = [] # type: typing.List[Decoder]Response.contentTom Christiebefore adoption4c55113
line 651why, one step back651 values = self.headers.getlist("content-encoding", split_commas=True)Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 652–654why, one step back652 for value in values:653 value = value.strip().lower()654 decoder_cls = SUPPORTED_DECODERS[value]Clean up response interfaceTom Christiebefore adoption4d908d0
lines 655–664why, one step back655 decoders.append(decoder_cls())656657 if len(decoders) == 1:658 self._decoder = decoders[0]659 elif len(decoders) > 1:660 self._decoder = MultiDecoder(decoders)661 else:662 self._decoder = IdentityDecoder()663664 return self._decoderMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 665–669why, one step back665666 async def read(self) -> bytes:667 """668 Read and return the response content.669 """Response.contentTom Christiebefore adoption4c55113
line 670why, one step back670 if not hasattr(self, "_content"):Merge pull request #53 from yunstanford/patch-0Tom Christiebefore adoption21ac95a
line 671why, one step back671 self._content = b"".join([part async for part in self.stream()])Response.contentTom Christiebefore adoption4c55113
line 672why, one step back672 return self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 673–678why, one step back673674 async def stream(self) -> typing.AsyncIterator[bytes]:675 """676 A byte-iterator over the decoded response content.677 This allows us to handle gzip, deflate, and brotli encoded responses.678 """Response.contentTom Christiebefore adoption4c55113
lines 679–680why, one step back679 if hasattr(self, "_content"):680 yield self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 681–689why, one step back681 else:682 async for chunk in self.raw():683 yield self.decoder.decode(chunk)684 yield self.decoder.flush()685686 async def raw(self) -> typing.AsyncIterator[bytes]:687 """688 A byte-iterator over the raw response content.689 """Response.contentTom Christiebefore adoption4c55113
lines 690–701why, one step back690 if hasattr(self, "_raw_content"):691 yield self._raw_content692 else:693 if self.is_stream_consumed:694 raise StreamConsumed()695 if self.is_closed:696 raise ResponseClosed()697698 self.is_stream_consumed = True699 async for part in self._raw_stream:700 yield part701 await self.close()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 702–715why, one step back702703 async def close(self) -> None:704 """705 Close the response and release the connection.706 Automatically called if the response body is read to completion.707 """708 if not self.is_closed:709 self.is_closed = True710 if self.on_close is not None:711 await self.on_close()712713 @property714 def is_redirect(self) -> bool:715 return (Finessing interfaceTom Christiebefore adoptiond7619a9
lines 716–717why, one step back716 self.status_code717 in (Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369
lines 718–722why, one step back718 codes.MOVED_PERMANENTLY,719 codes.FOUND,720 codes.SEE_OTHER,721 codes.TEMPORARY_REDIRECT,722 codes.PERMANENT_REDIRECT,Finessing interfaceTom Christiebefore adoptiond7619a9
lines 723–724why, one step back723 )724 and "location" in self.headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 725why, one step back725 )Still truckin' onTom Christiebefore adoption6cb5c0d
line 726why, one step back726Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 727–744why, one step back727 def raise_for_status(self) -> None:728 """729 Raise the `HttpError` if one occurred.730 """731 message = (732 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"733 "For more information check: https://httpstatuses.com/{0.status_code}"734 )735736 if 400 <= self.status_code < 500:737 message = message.format(self, error_type="Client Error")738 elif 500 <= self.status_code < 600:739 message = message.format(self, error_type="Server Error")740 else:741 message = ""742743 if message:744 raise HttpError(message)Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 745–746why, one step back745746 def __repr__(self) -> str:repr change: <SyncResponse ...> -> <Response ...>Tom Christiebefore adoption73d5fca
line 747why, one step back747 return f"<Response({self.status_code}, {self.reason_phrase!r})>"Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 748–823why, one step back748749750class SyncResponse:751 """752 A thread-synchronous response. This class proxies onto a `Response`753 instance, providing standard synchronous interfaces where required.754 """755756 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):757 self._response = response758 self._loop = loop759760 @property761 def status_code(self) -> int:762 return self._response.status_code763764 @property765 def reason_phrase(self) -> str:766 return self._response.reason_phrase767768 @property769 def protocol(self) -> typing.Optional[str]:770 return self._response.protocol771772 @property773 def url(self) -> typing.Optional[URL]:774 return self._response.url775776 @property777 def request(self) -> typing.Optional[Request]:778 return self._response.request779780 @property781 def headers(self) -> Headers:782 return self._response.headers783784 @property785 def content(self) -> bytes:786 return self._response.content787788 @property789 def text(self) -> str:790 return self._response.text791792 @property793 def encoding(self) -> str:794 return self._response.encoding795796 @property797 def is_redirect(self) -> bool:798 return self._response.is_redirect799800 def raise_for_status(self) -> None:801 return self._response.raise_for_status()802803 def read(self) -> bytes:804 return self._loop.run_until_complete(self._response.read())805806 def stream(self) -> typing.Iterator[bytes]:807 inner = self._response.stream()808 while True:809 try:810 yield self._loop.run_until_complete(inner.__anext__())811 except StopAsyncIteration as exc:812 break813814 def raw(self) -> typing.Iterator[bytes]:815 inner = self._response.raw()816 while True:817 try:818 yield self._loop.run_until_complete(inner.__anext__())819 except StopAsyncIteration as exc:820 break821822 def close(self) -> None:823 return self._loop.run_until_complete(self._response.close())Merge pull request #56 from yeraydiazdiaz/test-additional-http-methodsTom Christiebefore adoption87cab4c
lines 824–825why, one step back824825 def __repr__(self) -> str:repr change: <SyncResponse ...> -> <Response ...>Tom Christiebefore adoption73d5fca
line 826why, one step back826 return f"<Response({self.status_code}, {self.reason_phrase!r})>"