Skip to content
Myr

datastructures.py

This file

Path

httpcore/datastructures.py

280 lines · 8.3 KiB · Python

Last changed by

Merge pull request #15 from encode/module-renamingTom Christiebefore adoption0c20fba

History of this file

Take it

Add response.reasonTom Christiebefore adoptionfc7cf9d

line 1why, one step back
1import http

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

line 2why, one step back
2import typing

Merge pull request #12 from encode/refactorTom Christiebefore adoption39eb55b

line 3why, one step back
3from types import TracebackType

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 4–5why, one step back
4from urllib.parse import urlsplit
5

Merge pull request #12 from encode/refactorTom Christiebefore adoption39eb55b

line 6why, one step back
6from .config import SSLConfig, TimeoutConfig

Merge pull request #3 from encode/request-auto-headersTom Christiebefore adoptionfae53e2

lines 7–13why, one step back
7from .decoders import (
8 ACCEPT_ENCODING,9 SUPPORTED_DECODERS,10 Decoder,11 IdentityDecoder,12 MultiDecoder,13)

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 14–65why, one step back
14from .exceptions import ResponseClosed, StreamConsumed
151617class URL:18 def __init__(self, url: str = "") -> None:19 self.components = urlsplit(url)20 if not self.components.scheme:21 raise ValueError("No scheme included in URL.")22 if self.components.scheme not in ("http", "https"):23 raise ValueError('URL scheme must be "http" or "https".')24 if not self.components.hostname:25 raise ValueError("No hostname included in URL.")2627 @property28 def scheme(self) -> str:29 return self.components.scheme3031 @property32 def netloc(self) -> str:33 return self.components.netloc3435 @property36 def path(self) -> str:37 return self.components.path3839 @property40 def query(self) -> str:41 return self.components.query4243 @property44 def hostname(self) -> str:45 return self.components.hostname4647 @property48 def port(self) -> int:49 port = self.components.port50 if port is None:51 return {"https": 443, "http": 80}[self.scheme]52 return port5354 @property55 def target(self) -> str:56 path = self.path or "/"57 query = self.query58 if query:59 return path + "?" + query60 return path6162 @property63 def is_secure(self) -> bool:64 return self.components.scheme == "https"65

Merge pull request #12 from encode/refactorTom Christiebefore adoption39eb55b

lines 66–68why, one step back
66 @property
67 def origin(self) -> "Origin":68 return Origin(self)

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

line 69why, one step back
69

Merge pull request #12 from encode/refactorTom Christiebefore adoption39eb55b

lines 70–74why, one step back
70
71class Origin:72 def __init__(self, url: typing.Union[str, URL]) -> None:73 if isinstance(url, str):74 url = URL(url)

Merge pull request #15 from encode/module-renamingTom Christiebefore adoption0c20fba

lines 75–76why, one step back
75 self.is_ssl = url.scheme == "https"
76 self.hostname = url.hostname.lower()

Merge pull request #12 from encode/refactorTom Christiebefore adoption39eb55b

lines 77–81why, one step back
77 self.port = url.port
7879 def __eq__(self, other: typing.Any) -> bool:80 return (81 isinstance(other, self.__class__)

Merge pull request #15 from encode/module-renamingTom Christiebefore adoption0c20fba

line 82why, one step back
82 and self.is_ssl == other.is_ssl

Merge pull request #12 from encode/refactorTom Christiebefore adoption39eb55b

lines 83–87why, one step back
83 and self.hostname == other.hostname
84 and self.port == other.port85 )8687 def __hash__(self) -> int:

Merge pull request #15 from encode/module-renamingTom Christiebefore adoption0c20fba

line 88why, one step back
88 return hash((self.is_ssl, self.hostname, self.port))

Merge pull request #12 from encode/refactorTom Christiebefore adoption39eb55b

lines 89–90why, one step back
89
90

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 91–94why, one step back
91class Request:
92 def __init__(93 self,94 method: str,

Merge pull request #3 from encode/request-auto-headersTom Christiebefore adoptionfae53e2

line 95why, one step back
95 url: typing.Union[str, URL],

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 96–99why, one step back
96 *,
97 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),98 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",99 ):

Merge pull request #13 from encode/syncTom Christiebefore adoption903a961

line 100why, one step back
100 self.method = method.upper()

Merge pull request #3 from encode/request-auto-headersTom Christiebefore adoptionfae53e2

line 101why, one step back
101 self.url = URL(url) if isinstance(url, str) else url

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 102–108why, one step back
102 self.headers = list(headers)
103 if isinstance(body, bytes):104 self.is_streaming = False105 self.body = body106 else:107 self.is_streaming = True108 self.body_aiter = body

Merge pull request #3 from encode/request-auto-headersTom Christiebefore adoptionfae53e2

line 109why, one step back
109 self.headers = self._auto_headers() + self.headers

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

line 110why, one step back
110

Merge pull request #3 from encode/request-auto-headersTom Christiebefore adoptionfae53e2

lines 111–139why, one step back
111 def _auto_headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:
112 has_host = False113 has_content_length = False114 has_accept_encoding = False115116 for header, value in self.headers:117 header = header.strip().lower()118 if header == b"host":119 has_host = True120 elif header in (b"content-length", b"transfer-encoding"):121 has_content_length = True122 elif header == b"accept-encoding":123 has_accept_encoding = True124125 headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]126127 if not has_host:128 headers.append((b"host", self.url.netloc.encode("ascii")))129 if not has_content_length:130 if self.is_streaming:131 headers.append((b"transfer-encoding", b"chunked"))132 elif self.body:133 content_length = str(len(self.body)).encode()134 headers.append((b"content-length", content_length))135 if not has_accept_encoding:136 headers.append((b"accept-encoding", ACCEPT_ENCODING))137138 return headers139

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 140–151why, one step back
140 async def stream(self) -> typing.AsyncIterator[bytes]:
141 assert self.is_streaming142143 async for part in self.body_aiter:144 yield part145146147class Response:148 def __init__(149 self,150 status_code: int,151 *,

Add response.reasonTom Christiebefore adoptionfc7cf9d

line 152why, one step back
152 reason: typing.Optional[str] = None,

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 153–157why, one step back
153 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),
154 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",155 on_close: typing.Callable = None,156 ):157 self.status_code = status_code

Add response.reasonTom Christiebefore adoptionfc7cf9d

lines 158–164why, one step back
158 if not reason:
159 try:160 self.reason = http.HTTPStatus(status_code).phrase161 except ValueError as exc:162 self.reason = ""163 else:164 self.reason = reason

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 165–168why, one step back
165 self.headers = list(headers)
166 self.on_close = on_close167 self.is_closed = False168 self.is_streamed = False

Merge pull request #2 from encode/decompressionTom Christiebefore adoption60befed

lines 169–184why, one step back
169
170 decoders = [] # type: typing.List[Decoder]171 for header, value in self.headers:172 if header.strip().lower() == b"content-encoding":173 for part in value.split(b","):174 part = part.strip().lower()175 decoder_cls = SUPPORTED_DECODERS[part]176 decoders.append(decoder_cls())177178 if len(decoders) == 0:179 self.decoder = IdentityDecoder() # type: Decoder180 elif len(decoders) == 1:181 self.decoder = decoders[0]182 else:183 self.decoder = MultiDecoder(decoders)184

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 185–186why, one step back
185 if isinstance(body, bytes):
186 self.is_closed = True

Merge pull request #2 from encode/decompressionTom Christiebefore adoption60befed

line 187why, one step back
187 self.body = self.decoder.decode(body) + self.decoder.flush()

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 188–204why, one step back
188 else:
189 self.body_aiter = body190191 async def read(self) -> bytes:192 """193 Read and return the response content.194 """195 if not hasattr(self, "body"):196 body = b""197 async for part in self.stream():198 body += part199 self.body = body200 return self.body201202 async def stream(self) -> typing.AsyncIterator[bytes]:203 """204 A byte-iterator over the decoded response content.

Merge pull request #3 from encode/request-auto-headersTom Christiebefore adoptionfae53e2

line 205why, one step back
205 This allows us to handle gzip, deflate, and brotli encoded responses.

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 206–227why, one step back
206 """
207 if hasattr(self, "body"):208 yield self.body209 else:210 async for chunk in self.raw():211 yield self.decoder.decode(chunk)212 yield self.decoder.flush()213214 async def raw(self) -> typing.AsyncIterator[bytes]:215 """216 A byte-iterator over the raw response content.217 """218 if self.is_streamed:219 raise StreamConsumed()220 if self.is_closed:221 raise ResponseClosed()222 self.is_streamed = True223 async for part in self.body_aiter:224 yield part225 await self.close()226227 async def close(self) -> None:

Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a

lines 228–231why, one step back
228 """
229 Close the response and release the connection.230 Automatically called if the response body is read to completion.231 """

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 232–235why, one step back
232 if not self.is_closed:
233 self.is_closed = True234 if self.on_close is not None:235 await self.on_close()

Merge pull request #12 from encode/refactorTom Christiebefore adoption39eb55b

lines 236–280why, one step back
236
237238class Client:239 async def request(240 self,241 method: str,242 url: typing.Union[str, URL],243 *,244 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),245 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",246 ssl: typing.Optional[SSLConfig] = None,247 timeout: typing.Optional[TimeoutConfig] = None,248 stream: bool = False,249 ) -> Response:250 request = Request(method, url, headers=headers, body=body)251 response = await self.send(request, ssl=ssl, timeout=timeout)252 if not stream:253 try:254 await response.read()255 finally:256 await response.close()257 return response258259 async def send(260 self,261 request: Request,262 *,263 ssl: typing.Optional[SSLConfig] = None,264 timeout: typing.Optional[TimeoutConfig] = None,265 ) -> Response:266 raise NotImplementedError() # pragma: nocover267268 async def close(self) -> None:269 raise NotImplementedError() # pragma: nocover270271 async def __aenter__(self) -> "Client":272 return self273274 async def __aexit__(275 self,276 exc_type: typing.Type[BaseException] = None,277 exc_value: BaseException = None,278 traceback: TracebackType = None,279 ) -> None:280 await self.close()