Skip to content
Myr

models.py

This file

Path

httpcore/models.py

413 lines · 12.3 KiB · Python

Last changed by

Finessing interfaceTom Christiebefore adoptiond7619a9

History of this file

Take it

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 1–12why, one step back
1import typing
2from 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, StreamConsumed

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 13–14why, one step back
13from .status_codes import codes
14from .utils import get_reason_phrase, normalize_header_key, normalize_header_value

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 15why, one step back
15

Finessing interfaceTom Christiebefore adoptiond7619a9

line 16why, one step back
16URLTypes = typing.Union["URL", str]

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 17why, one step back
17

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 18–26why, one step back
18HeaderTypes = 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]]2526

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 27why, one step back
27class URL:

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 28–33why, one step back
28 def __init__(self, url: URLTypes) -> None:
29 if isinstance(url, str):30 self.components = urlsplit(url)31 else:32 self.components = url.components33

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 34–248why, one step back
34 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 """127128 def __init__(self, headers: HeaderTypes = None) -> None:129 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 = [135 (normalize_header_key(k), normalize_header_value(v))136 for k, v in headers.items()137 ]138 else:139 self._list = [140 (normalize_header_key(k), normalize_header_value(v)) for k, v in headers141 ]142143 @property144 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:145 return self._list146147 def keys(self) -> typing.List[str]: # type: ignore148 return [key.decode("latin-1") for key, value in self._list]149150 def values(self) -> typing.List[str]: # type: ignore151 return [value.decode("latin-1") for key, value in self._list]152153 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore154 return [155 (key.decode("latin-1"), value.decode("latin-1"))156 for key, value in self._list157 ]158159 def get(self, key: str, default: typing.Any = None) -> typing.Any:160 try:161 return self[key]162 except KeyError:163 return default164165 def getlist(self, key: str) -> typing.List[str]:166 get_header_key = key.lower().encode("latin-1")167 return [168 item_value.decode("latin-1")169 for item_key, item_value in self._list170 if item_key == get_header_key171 ]172173 def __getitem__(self, key: str) -> str:174 get_header_key = key.lower().encode("latin-1")175 for header_key, header_value in self._list:176 if header_key == get_header_key:177 return header_value.decode("latin-1")178 raise KeyError(key)179180 def __setitem__(self, key: str, value: str) -> None:181 """182 Set the header `key` to `value`, removing any duplicate entries.183 Retains insertion order.184 """185 set_key = key.lower().encode("latin-1")186 set_value = value.encode("latin-1")187188 found_indexes = []189 for idx, (item_key, item_value) in enumerate(self._list):190 if item_key == set_key:191 found_indexes.append(idx)192193 for idx in reversed(found_indexes[1:]):194 del self._list[idx]195196 if found_indexes:197 idx = found_indexes[0]198 self._list[idx] = (set_key, set_value)199 else:200 self._list.append((set_key, set_value))201202 def __delitem__(self, key: str) -> None:203 """204 Remove the header `key`.205 """206 del_key = key.lower().encode("latin-1")207208 pop_indexes = []209 for idx, (item_key, item_value) in enumerate(self._list):210 if item_key == del_key:211 pop_indexes.append(idx)212213 for idx in reversed(pop_indexes):214 del self._list[idx]215216 def __contains__(self, key: typing.Any) -> bool:217 get_header_key = key.lower().encode("latin-1")218 for header_key, header_value in self._list:219 if header_key == get_header_key:220 return True221 return False222223 def __iter__(self) -> typing.Iterator[typing.Any]:224 return iter(self.keys())225226 def __len__(self) -> int:227 return len(self._list)228229 def __eq__(self, other: typing.Any) -> bool:230 if not isinstance(other, Headers):231 return False232 return sorted(self._list) == sorted(other._list)233234 def __repr__(self) -> str:235 class_name = self.__class__.__name__236 as_dict = dict(self.items())237 if len(as_dict) == len(self):238 return f"{class_name}({as_dict!r})"239 return f"{class_name}(raw={self.raw!r})"240241242class Request:243 def __init__(244 self,245 method: str,246 url: typing.Union[str, URL],247 *,248 headers: HeaderTypes = None,

Finessing interfaceTom Christiebefore adoptiond7619a9

line 249why, one step back
249 body: BodyTypes = b"",

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 250–307why, one step back
250 ):
251 self.method = method.upper()252 self.url = URL(url) if isinstance(url, str) else url253 if isinstance(body, bytes):254 self.is_streaming = False255 self.body = body256 else:257 self.is_streaming = True258 self.body_aiter = body259 self.headers = Headers(headers)260261 async def read(self) -> bytes:262 """263 Read and return the response content.264 """265 if not hasattr(self, "body"):266 body = b""267 async for part in self.stream():268 body += part269 self.body = body270 return self.body271272 async def stream(self) -> typing.AsyncIterator[bytes]:273 if self.is_streaming:274 async for part in self.body_aiter:275 yield part276 elif self.body:277 yield self.body278279 def prepare(self) -> None:280 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]281282 has_host = "host" in self.headers283 has_content_length = (284 "content-length" in self.headers or "transfer-encoding" in self.headers285 )286 has_accept_encoding = "accept-encoding" in self.headers287288 if not has_host:289 auto_headers.append((b"host", self.url.netloc.encode("ascii")))290 if not has_content_length:291 if self.is_streaming:292 auto_headers.append((b"transfer-encoding", b"chunked"))293 elif self.body:294 content_length = str(len(self.body)).encode()295 auto_headers.append((b"content-length", content_length))296 if not has_accept_encoding:297 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))298299 for item in reversed(auto_headers):300 self.headers.raw.insert(0, item)301302303class Response:304 def __init__(305 self,306 status_code: int,307 *,

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 308–311why, one step back
308 reason_phrase: str = None,
309 protocol: str = None,310 headers: HeaderTypes = None,311 body: BodyTypes = b"",

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 312–316why, one step back
312 on_close: typing.Callable = None,
313 request: Request = None,314 history: typing.List["Response"] = None,315 ):316 self.status_code = status_code

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 317–318why, one step back
317 if reason_phrase is None:
318 self.reason_phrase = get_reason_phrase(status_code)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 319why, one step back
319 else:

Finessing interfaceTom Christiebefore adoptiond7619a9

line 320why, one step back
320 self.reason_phrase = reason_phrase

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 321–348why, one step back
321 self.protocol = protocol
322 self.headers = Headers(headers)323 self.on_close = on_close324 self.is_closed = False325 self.is_streamed = False326327 decoders = [] # type: typing.List[Decoder]328 value = self.headers.get("content-encoding", "identity")329 for part in value.split(","):330 part = part.strip().lower()331 decoder_cls = SUPPORTED_DECODERS[part]332 decoders.append(decoder_cls())333334 if len(decoders) == 0:335 self.decoder = IdentityDecoder() # type: Decoder336 elif len(decoders) == 1:337 self.decoder = decoders[0]338 else:339 self.decoder = MultiDecoder(decoders)340341 if isinstance(body, bytes):342 self.is_closed = True343 self.body = self.decoder.decode(body) + self.decoder.flush()344 else:345 self.body_aiter = body346347 self.request = request348 self.history = [] if history is None else list(history)

response.next()Tom Christiebefore adoptiond652479

line 349why, one step back
349 self.next = None # typing.Optional[typing.Callable]

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 350–403why, one step back
350
351 @property352 def url(self) -> typing.Optional[URL]:353 return None if self.request is None else self.request.url354355 async def read(self) -> bytes:356 """357 Read and return the response content.358 """359 if not hasattr(self, "body"):360 body = b""361 async for part in self.stream():362 body += part363 self.body = body364 return self.body365366 async def stream(self) -> typing.AsyncIterator[bytes]:367 """368 A byte-iterator over the decoded response content.369 This allows us to handle gzip, deflate, and brotli encoded responses.370 """371 if hasattr(self, "body"):372 yield self.body373 else:374 async for chunk in self.raw():375 yield self.decoder.decode(chunk)376 yield self.decoder.flush()377378 async def raw(self) -> typing.AsyncIterator[bytes]:379 """380 A byte-iterator over the raw response content.381 """382 if self.is_streamed:383 raise StreamConsumed()384 if self.is_closed:385 raise ResponseClosed()386 self.is_streamed = True387 async for part in self.body_aiter:388 yield part389 await self.close()390391 async def close(self) -> None:392 """393 Close the response and release the connection.394 Automatically called if the response body is read to completion.395 """396 if not self.is_closed:397 self.is_closed = True398 if self.on_close is not None:399 await self.on_close()400401 @property402 def is_redirect(self) -> bool:403 return (

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 404–412why, one step back
404 self.status_code
405 in (406 codes.moved_permanently,407 codes.found,408 codes.see_other,409 codes.temporary_redirect,410 codes.permanent_redirect,411 )412 and "location" in self.headers

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 413why, one step back
413 )