datastructures.py
This file
Path
httpcore/datastructures.py
200 lines · 6.0 KiB · Python
Last changed by
Rejig response streaming/closingTom Christiebefore adoption63d73ad
History of this fileTake it
Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 1–3why, one step back1import typing2from urllib.parse import urlsplit3Add auto headers on RequestTom Christiebefore adoption042dd22
lines 4–10why, one step back4from .decoders import (5 ACCEPT_ENCODING,6 SUPPORTED_DECODERS,7 Decoder,8 IdentityDecoder,9 MultiDecoder,10)Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 11–67why, one step back11from .exceptions import ResponseClosed, StreamConsumed121314class URL:15 def __init__(self, url: str = "") -> None:16 self.components = urlsplit(url)17 if not self.components.scheme:18 raise ValueError("No scheme included in URL.")19 if self.components.scheme not in ("http", "https"):20 raise ValueError('URL scheme must be "http" or "https".')21 if not self.components.hostname:22 raise ValueError("No hostname included in URL.")2324 @property25 def scheme(self) -> str:26 return self.components.scheme2728 @property29 def netloc(self) -> str:30 return self.components.netloc3132 @property33 def path(self) -> str:34 return self.components.path3536 @property37 def query(self) -> str:38 return self.components.query3940 @property41 def hostname(self) -> str:42 return self.components.hostname4344 @property45 def port(self) -> int:46 port = self.components.port47 if port is None:48 return {"https": 443, "http": 80}[self.scheme]49 return port5051 @property52 def target(self) -> str:53 path = self.path or "/"54 query = self.query55 if query:56 return path + "?" + query57 return path5859 @property60 def is_secure(self) -> bool:61 return self.components.scheme == "https"626364class Request:65 def __init__(66 self,67 method: str,Add auto headers on RequestTom Christiebefore adoption042dd22
line 68why, one step back68 url: typing.Union[str, URL],Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 69–73why, one step back69 *,70 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),71 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",72 ):73 self.method = methodAdd auto headers on RequestTom Christiebefore adoption042dd22
line 74why, one step back74 self.url = URL(url) if isinstance(url, str) else urlMerge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 75–81why, one step back75 self.headers = list(headers)76 if isinstance(body, bytes):77 self.is_streaming = False78 self.body = body79 else:80 self.is_streaming = True81 self.body_aiter = bodyAdd auto headers on RequestTom Christiebefore adoption042dd22
line 82why, one step back82 self.headers = self._auto_headers() + self.headersMerge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
line 83why, one step back83Add auto headers on RequestTom Christiebefore adoption042dd22
lines 84–112why, one step back84 def _auto_headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:85 has_host = False86 has_content_length = False87 has_accept_encoding = False8889 for header, value in self.headers:90 header = header.strip().lower()91 if header == b"host":92 has_host = True93 elif header in (b"content-length", b"transfer-encoding"):94 has_content_length = True95 elif header == b"accept-encoding":96 has_accept_encoding = True9798 headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]99100 if not has_host:101 headers.append((b"host", self.url.netloc.encode("ascii")))102 if not has_content_length:103 if self.is_streaming:104 headers.append((b"transfer-encoding", b"chunked"))105 elif self.body:106 content_length = str(len(self.body)).encode()107 headers.append((b"content-length", content_length))108 if not has_accept_encoding:109 headers.append((b"accept-encoding", ACCEPT_ENCODING))110111 return headers112Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 113–133why, one step back113 async def stream(self) -> typing.AsyncIterator[bytes]:114 assert self.is_streaming115116 async for part in self.body_aiter:117 yield part118119120class Response:121 def __init__(122 self,123 status_code: int,124 *,125 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),126 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",127 on_close: typing.Callable = None,128 ):129 self.status_code = status_code130 self.headers = list(headers)131 self.on_close = on_close132 self.is_closed = False133 self.is_streamed = FalseMerge pull request #2 from encode/decompressionTom Christiebefore adoption60befed
lines 134–149why, one step back134135 decoders = [] # type: typing.List[Decoder]136 for header, value in self.headers:137 if header.strip().lower() == b"content-encoding":138 for part in value.split(b","):139 part = part.strip().lower()140 decoder_cls = SUPPORTED_DECODERS[part]141 decoders.append(decoder_cls())142143 if len(decoders) == 0:144 self.decoder = IdentityDecoder() # type: Decoder145 elif len(decoders) == 1:146 self.decoder = decoders[0]147 else:148 self.decoder = MultiDecoder(decoders)149Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 150–151why, one step back150 if isinstance(body, bytes):151 self.is_closed = TrueMerge pull request #2 from encode/decompressionTom Christiebefore adoption60befed
line 152why, one step back152 self.body = self.decoder.decode(body) + self.decoder.flush()Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 153–169why, one step back153 else:154 self.body_aiter = body155156 async def read(self) -> bytes:157 """158 Read and return the response content.159 """160 if not hasattr(self, "body"):161 body = b""162 async for part in self.stream():163 body += part164 self.body = body165 return self.body166167 async def stream(self) -> typing.AsyncIterator[bytes]:168 """169 A byte-iterator over the decoded response content.Add auto headers on RequestTom Christiebefore adoption042dd22
line 170why, one step back170 This allows us to handle gzip, deflate, and brotli encoded responses.Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 171–192why, one step back171 """172 if hasattr(self, "body"):173 yield self.body174 else:175 async for chunk in self.raw():176 yield self.decoder.decode(chunk)177 yield self.decoder.flush()178179 async def raw(self) -> typing.AsyncIterator[bytes]:180 """181 A byte-iterator over the raw response content.182 """183 if self.is_streamed:184 raise StreamConsumed()185 if self.is_closed:186 raise ResponseClosed()187 self.is_streamed = True188 async for part in self.body_aiter:189 yield part190 await self.close()191192 async def close(self) -> None:Rejig response streaming/closingTom Christiebefore adoption63d73ad
lines 193–196why, one step back193 """194 Close the response and release the connection.195 Automatically called if the response body is read to completion.196 """Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 197–200why, one step back197 if not self.is_closed:198 self.is_closed = True199 if self.on_close is not None:200 await self.on_close()