models.py
This file
Path
httpcore/models.py
502 lines · 15.2 KiB · Python
Last changed by
Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
History of this fileTake it
Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 1–12why, one step back1import typing2from urllib.parse import urlsplit34from .config import SSLConfig, TimeoutConfig5from .decoders import (6 ACCEPT_ENCODING,7 SUPPORTED_DECODERS,8 Decoder,9 IdentityDecoder,10 MultiDecoder,11)12from .exceptions import ResponseClosed, StreamConsumedFinessing interfaceTom Christiebefore adoptiond7619a9
lines 13–14why, one step back13from .status_codes import codes14from .utils import get_reason_phrase, normalize_header_key, normalize_header_valueMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 15why, one step back15Finessing interfaceTom Christiebefore adoptiond7619a9
line 16why, one step back16URLTypes = typing.Union["URL", str]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 17why, one step back17Finessing interfaceTom Christiebefore adoptiond7619a9
lines 18–26why, one step back18HeaderTypes = typing.Union[19 "Headers",20 typing.Dict[typing.AnyStr, typing.AnyStr],21 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],22]2324BodyTypes = typing.Union[bytes, typing.AsyncIterator[bytes]]2526Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 27why, one step back27class URL:Finessing interfaceTom Christiebefore adoptiond7619a9
lines 28–33why, one step back28 def __init__(self, url: URLTypes) -> None:29 if isinstance(url, str):30 self.components = urlsplit(url)31 else:32 self.components = url.components33Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 34–127why, one step back34 if not self.components.scheme:35 raise ValueError("No scheme included in URL.")36 if self.components.scheme not in ("http", "https"):37 raise ValueError('URL scheme must be "http" or "https".')38 if not self.components.hostname:39 raise ValueError("No hostname included in URL.")4041 @property42 def scheme(self) -> str:43 return self.components.scheme4445 @property46 def netloc(self) -> str:47 return self.components.netloc4849 @property50 def path(self) -> str:51 return self.components.path5253 @property54 def query(self) -> str:55 return self.components.query5657 @property58 def fragment(self) -> str:59 return self.components.fragment6061 @property62 def hostname(self) -> str:63 return self.components.hostname6465 @property66 def port(self) -> int:67 port = self.components.port68 if port is None:69 return {"https": 443, "http": 80}[self.scheme]70 return port7172 @property73 def full_path(self) -> str:74 path = self.path or "/"75 query = self.query76 if query:77 return path + "?" + query78 return path7980 @property81 def is_secure(self) -> bool:82 return self.components.scheme == "https"8384 @property85 def origin(self) -> "Origin":86 return Origin(self)8788 def __hash__(self) -> int:89 return hash(str(self))9091 def __eq__(self, other: typing.Any) -> bool:92 return isinstance(other, URL) and str(self) == str(other)9394 def __str__(self) -> str:95 return self.components.geturl()9697 def __repr__(self) -> str:98 class_name = self.__class__.__name__99 url_str = str(self)100 return f"{class_name}({url_str!r})"101102103class Origin:104 def __init__(self, url: typing.Union[str, URL]) -> None:105 if isinstance(url, str):106 url = URL(url)107 self.is_ssl = url.scheme == "https"108 self.hostname = url.hostname.lower()109 self.port = url.port110111 def __eq__(self, other: typing.Any) -> bool:112 return (113 isinstance(other, self.__class__)114 and self.is_ssl == other.is_ssl115 and self.hostname == other.hostname116 and self.port == other.port117 )118119 def __hash__(self) -> int:120 return hash((self.is_ssl, self.hostname, self.port))121122123class Headers(typing.MutableMapping[str, str]):124 """125 A case-insensitive multidict.126 """127Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 128why, one step back128 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 129–134why, one step back129 if headers is None:130 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]131 elif isinstance(headers, Headers):132 self._list = list(headers.raw)133 elif isinstance(headers, dict):134 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 135why, one step back135 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 136–139why, one step back136 for k, v in headers.items()137 ]138 else:139 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 140–141why, one step back140 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))141 for k, v in headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 142why, one step back142 ]Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 143why, one step back143 self._encoding = encodingMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 144–145why, one step back144145 @propertyRejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 146–174why, one step back146 def encoding(self) -> str:147 """148 Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be149 seen in the wild.150 """151 if self._encoding is None:152 for encoding in ["ascii", "utf-8"]:153 for key, value in self.raw:154 try:155 key.decode(encoding)156 value.decode(encoding)157 except UnicodeDecodeError:158 break159 else:160 # The else block runs if 'break' did not occur, meaning161 # all values fitted the encoding.162 self._encoding = encoding163 break164 else:165 # The ISO-8859-1 encoding covers all 256 code points in a byte,166 # so will never raise decode errors.167 self._encoding = "iso-8859-1"168 return self._encoding169170 @encoding.setter171 def encoding(self, value: str) -> None:172 self._encoding = value173174 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 175why, one step back175 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 176–179why, one step back176 """177 Returns a list of the raw header items, as byte pairs.178 May be mutated in-place.179 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 180–182why, one step back180 return self._list181182 def keys(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 183why, one step back183 return [key.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 184–185why, one step back184185 def values(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 186why, one step back186 return [value.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 187–189why, one step back187188 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore189 return [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 190why, one step back190 (key.decode(self.encoding), value.decode(self.encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 191–199why, one step back191 for key, value in self._list192 ]193194 def get(self, key: str, default: typing.Any = None) -> typing.Any:195 try:196 return self[key]197 except KeyError:198 return default199Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 200–214why, one step back200 def getlist(self, key: str, default: typing.Any = None, split_commas = None) -> typing.List[str]:201 """202 Return multiple header values.203204 If there are header values that include commas, then we default to205 spliting them into multiple results, except for Set-Cookie.206207 See: https://tools.ietf.org/html/rfc7230#section-3.2.2208 """209 get_header_key = key.lower().encode(self.encoding)210 if split_commas is None:211 split_commas = get_header_key != b'set-cookie'212213 values = [214 item_value.decode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 215–218why, one step back215 for item_key, item_value in self._list216 if item_key == get_header_key217 ]218Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 219–229why, one step back219 if not values:220 return [] if default is None else default221222 if not split_commas:223 return values224225 split_values = []226 for value in values:227 split_values.extend([item.strip() for item in value.split(",")])228 return split_values229Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 230why, one step back230 def __getitem__(self, key: str) -> str:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 231–239why, one step back231 """232 Return a single header value.233234 If there are multiple headers with the same key, then we concatenate235 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2236 """237 normalized_key = key.lower().encode(self.encoding)238239 items = []Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 240why, one step back240 for header_key, header_value in self._list:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 241–246why, one step back241 if header_key == normalized_key:242 items.append(header_value.decode(self.encoding))243244 if items:245 return ", ".join(items)246Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 247–253why, one step back247 raise KeyError(key)248249 def __setitem__(self, key: str, value: str) -> None:250 """251 Set the header `key` to `value`, removing any duplicate entries.252 Retains insertion order.253 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 254–255why, one step back254 set_key = key.lower().encode(self.encoding)255 set_value = value.encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 256–274why, one step back256257 found_indexes = []258 for idx, (item_key, item_value) in enumerate(self._list):259 if item_key == set_key:260 found_indexes.append(idx)261262 for idx in reversed(found_indexes[1:]):263 del self._list[idx]264265 if found_indexes:266 idx = found_indexes[0]267 self._list[idx] = (set_key, set_value)268 else:269 self._list.append((set_key, set_value))270271 def __delitem__(self, key: str) -> None:272 """273 Remove the header `key`.274 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 275why, one step back275 del_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 276–285why, one step back276277 pop_indexes = []278 for idx, (item_key, item_value) in enumerate(self._list):279 if item_key == del_key:280 pop_indexes.append(idx)281282 for idx in reversed(pop_indexes):283 del self._list[idx]284285 def __contains__(self, key: typing.Any) -> bool:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 286why, one step back286 get_header_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 287–304why, one step back287 for header_key, header_value in self._list:288 if header_key == get_header_key:289 return True290 return False291292 def __iter__(self) -> typing.Iterator[typing.Any]:293 return iter(self.keys())294295 def __len__(self) -> int:296 return len(self._list)297298 def __eq__(self, other: typing.Any) -> bool:299 if not isinstance(other, Headers):300 return False301 return sorted(self._list) == sorted(other._list)302303 def __repr__(self) -> str:304 class_name = self.__class__.__name__Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 305–309why, one step back305306 encoding_str = ""307 if self.encoding != "ascii":308 encoding_str = f", encoding={self.encoding!r}"309Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 310–311why, one step back310 as_dict = dict(self.items())311 if len(as_dict) == len(self):Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 312–314why, one step back312 return f"{class_name}({as_dict!r}{encoding_str})"313 as_list = self.items()314 return f"{class_name}({as_list!r}{encoding_str})"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 315–323why, one step back315316317class Request:318 def __init__(319 self,320 method: str,321 url: typing.Union[str, URL],322 *,323 headers: HeaderTypes = None,Finessing interfaceTom Christiebefore adoptiond7619a9
line 324why, one step back324 body: BodyTypes = b"",Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 325–382why, one step back325 ):326 self.method = method.upper()327 self.url = URL(url) if isinstance(url, str) else url328 if isinstance(body, bytes):329 self.is_streaming = False330 self.body = body331 else:332 self.is_streaming = True333 self.body_aiter = body334 self.headers = Headers(headers)335336 async def read(self) -> bytes:337 """338 Read and return the response content.339 """340 if not hasattr(self, "body"):341 body = b""342 async for part in self.stream():343 body += part344 self.body = body345 return self.body346347 async def stream(self) -> typing.AsyncIterator[bytes]:348 if self.is_streaming:349 async for part in self.body_aiter:350 yield part351 elif self.body:352 yield self.body353354 def prepare(self) -> None:355 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]356357 has_host = "host" in self.headers358 has_content_length = (359 "content-length" in self.headers or "transfer-encoding" in self.headers360 )361 has_accept_encoding = "accept-encoding" in self.headers362363 if not has_host:364 auto_headers.append((b"host", self.url.netloc.encode("ascii")))365 if not has_content_length:366 if self.is_streaming:367 auto_headers.append((b"transfer-encoding", b"chunked"))368 elif self.body:369 content_length = str(len(self.body)).encode()370 auto_headers.append((b"content-length", content_length))371 if not has_accept_encoding:372 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))373374 for item in reversed(auto_headers):375 self.headers.raw.insert(0, item)376377378class Response:379 def __init__(380 self,381 status_code: int,382 *,Finessing interfaceTom Christiebefore adoptiond7619a9
lines 383–386why, one step back383 reason_phrase: str = None,384 protocol: str = None,385 headers: HeaderTypes = None,386 body: BodyTypes = b"",Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 387–391why, one step back387 on_close: typing.Callable = None,388 request: Request = None,389 history: typing.List["Response"] = None,390 ):391 self.status_code = status_codeFinessing interfaceTom Christiebefore adoptiond7619a9
lines 392–393why, one step back392 if reason_phrase is None:393 self.reason_phrase = get_reason_phrase(status_code)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 394why, one step back394 else:Finessing interfaceTom Christiebefore adoptiond7619a9
line 395why, one step back395 self.reason_phrase = reason_phraseMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 396–409why, one step back396 self.protocol = protocol397 self.headers = Headers(headers)398 self.on_close = on_close399 self.is_closed = False400 self.is_streamed = False401402 if isinstance(body, bytes):403 self.is_closed = True404 self.body = self.decoder.decode(body) + self.decoder.flush()405 else:406 self.body_aiter = body407408 self.request = request409 self.history = [] if history is None else list(history)response.next()Tom Christiebefore adoptiond652479
line 410why, one step back410 self.next = None # typing.Optional[typing.Callable]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 411–413why, one step back411412 @property413 def url(self) -> typing.Optional[URL]:Clean up response interfaceTom Christiebefore adoption4d908d0
lines 414–418why, one step back414 """415 Returns the URL for which the request was made.416417 Requires that `request` was provided when instantiating the response.418 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 419why, one step back419 return None if self.request is None else self.request.urlClean up response interfaceTom Christiebefore adoption4d908d0
lines 420–428why, one step back420421 @property422 def decoder(self) -> Decoder:423 """424 Returns a decoder instance which can be used to decode the raw byte425 content, depending on the Content-Encoding used in the response.426 """427 if not hasattr(self, "_decoder"):428 decoders = [] # type: typing.List[Decoder]Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 429–432why, one step back429 values = self.headers.getlist("content-encoding", ["identity"])430 for value in values:431 value = value.strip().lower()432 decoder_cls = SUPPORTED_DECODERS[value]Clean up response interfaceTom Christiebefore adoption4d908d0
lines 433–442why, one step back433 decoders.append(decoder_cls())434435 if len(decoders) == 1:436 self._decoder = decoders[0]437 elif len(decoders) > 1:438 self._decoder = MultiDecoder(decoders)439 else:440 self._decoder = IdentityDecoder()441442 return self._decoderMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 443–492why, one step back443444 async def read(self) -> bytes:445 """446 Read and return the response content.447 """448 if not hasattr(self, "body"):449 body = b""450 async for part in self.stream():451 body += part452 self.body = body453 return self.body454455 async def stream(self) -> typing.AsyncIterator[bytes]:456 """457 A byte-iterator over the decoded response content.458 This allows us to handle gzip, deflate, and brotli encoded responses.459 """460 if hasattr(self, "body"):461 yield self.body462 else:463 async for chunk in self.raw():464 yield self.decoder.decode(chunk)465 yield self.decoder.flush()466467 async def raw(self) -> typing.AsyncIterator[bytes]:468 """469 A byte-iterator over the raw response content.470 """471 if self.is_streamed:472 raise StreamConsumed()473 if self.is_closed:474 raise ResponseClosed()475 self.is_streamed = True476 async for part in self.body_aiter:477 yield part478 await self.close()479480 async def close(self) -> None:481 """482 Close the response and release the connection.483 Automatically called if the response body is read to completion.484 """485 if not self.is_closed:486 self.is_closed = True487 if self.on_close is not None:488 await self.on_close()489490 @property491 def is_redirect(self) -> bool:492 return (Finessing interfaceTom Christiebefore adoptiond7619a9
lines 493–501why, one step back493 self.status_code494 in (495 codes.moved_permanently,496 codes.found,497 codes.see_other,498 codes.temporary_redirect,499 codes.permanent_redirect,500 )501 and "location" in self.headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 502why, one step back502 )