Skip to content
Myr

datastructures.py

This file

Path

httpcore/datastructures.py

209 lines · 6.2 KiB · Python

Last changed by

Add response.reasonTom Christiebefore adoptionfc7cf9d

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

lines 2–4why, one step back
2import typing
3from urllib.parse import urlsplit4

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

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

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

lines 12–68why, one step back
12from .exceptions import ResponseClosed, StreamConsumed
131415class URL:16 def __init__(self, url: str = "") -> None:17 self.components = urlsplit(url)18 if not self.components.scheme:19 raise ValueError("No scheme included in URL.")20 if self.components.scheme not in ("http", "https"):21 raise ValueError('URL scheme must be "http" or "https".')22 if not self.components.hostname:23 raise ValueError("No hostname included in URL.")2425 @property26 def scheme(self) -> str:27 return self.components.scheme2829 @property30 def netloc(self) -> str:31 return self.components.netloc3233 @property34 def path(self) -> str:35 return self.components.path3637 @property38 def query(self) -> str:39 return self.components.query4041 @property42 def hostname(self) -> str:43 return self.components.hostname4445 @property46 def port(self) -> int:47 port = self.components.port48 if port is None:49 return {"https": 443, "http": 80}[self.scheme]50 return port5152 @property53 def target(self) -> str:54 path = self.path or "/"55 query = self.query56 if query:57 return path + "?" + query58 return path5960 @property61 def is_secure(self) -> bool:62 return self.components.scheme == "https"636465class Request:66 def __init__(67 self,68 method: str,

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

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

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

lines 70–74why, one step back
70 *,
71 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),72 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",73 ):74 self.method = method

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

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

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

lines 76–82why, one step back
76 self.headers = list(headers)
77 if isinstance(body, bytes):78 self.is_streaming = False79 self.body = body80 else:81 self.is_streaming = True82 self.body_aiter = body

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

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

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

line 84why, one step back
84

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

lines 85–113why, one step back
85 def _auto_headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:
86 has_host = False87 has_content_length = False88 has_accept_encoding = False8990 for header, value in self.headers:91 header = header.strip().lower()92 if header == b"host":93 has_host = True94 elif header in (b"content-length", b"transfer-encoding"):95 has_content_length = True96 elif header == b"accept-encoding":97 has_accept_encoding = True9899 headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]100101 if not has_host:102 headers.append((b"host", self.url.netloc.encode("ascii")))103 if not has_content_length:104 if self.is_streaming:105 headers.append((b"transfer-encoding", b"chunked"))106 elif self.body:107 content_length = str(len(self.body)).encode()108 headers.append((b"content-length", content_length))109 if not has_accept_encoding:110 headers.append((b"accept-encoding", ACCEPT_ENCODING))111112 return headers113

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

lines 114–125why, one step back
114 async def stream(self) -> typing.AsyncIterator[bytes]:
115 assert self.is_streaming116117 async for part in self.body_aiter:118 yield part119120121class Response:122 def __init__(123 self,124 status_code: int,125 *,

Add response.reasonTom Christiebefore adoptionfc7cf9d

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

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

lines 127–131why, one step back
127 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),
128 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",129 on_close: typing.Callable = None,130 ):131 self.status_code = status_code

Add response.reasonTom Christiebefore adoptionfc7cf9d

lines 132–138why, one step back
132 if not reason:
133 try:134 self.reason = http.HTTPStatus(status_code).phrase135 except ValueError as exc:136 self.reason = ""137 else:138 self.reason = reason

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

lines 139–142why, one step back
139 self.headers = list(headers)
140 self.on_close = on_close141 self.is_closed = False142 self.is_streamed = False

Merge pull request #2 from encode/decompressionTom Christiebefore adoption60befed

lines 143–158why, one step back
143
144 decoders = [] # type: typing.List[Decoder]145 for header, value in self.headers:146 if header.strip().lower() == b"content-encoding":147 for part in value.split(b","):148 part = part.strip().lower()149 decoder_cls = SUPPORTED_DECODERS[part]150 decoders.append(decoder_cls())151152 if len(decoders) == 0:153 self.decoder = IdentityDecoder() # type: Decoder154 elif len(decoders) == 1:155 self.decoder = decoders[0]156 else:157 self.decoder = MultiDecoder(decoders)158

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

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

Merge pull request #2 from encode/decompressionTom Christiebefore adoption60befed

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

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

lines 162–178why, one step back
162 else:
163 self.body_aiter = body164165 async def read(self) -> bytes:166 """167 Read and return the response content.168 """169 if not hasattr(self, "body"):170 body = b""171 async for part in self.stream():172 body += part173 self.body = body174 return self.body175176 async def stream(self) -> typing.AsyncIterator[bytes]:177 """178 A byte-iterator over the decoded response content.

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

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

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

lines 180–201why, one step back
180 """
181 if hasattr(self, "body"):182 yield self.body183 else:184 async for chunk in self.raw():185 yield self.decoder.decode(chunk)186 yield self.decoder.flush()187188 async def raw(self) -> typing.AsyncIterator[bytes]:189 """190 A byte-iterator over the raw response content.191 """192 if self.is_streamed:193 raise StreamConsumed()194 if self.is_closed:195 raise ResponseClosed()196 self.is_streamed = True197 async for part in self.body_aiter:198 yield part199 await self.close()200201 async def close(self) -> None:

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

lines 202–205why, one step back
202 """
203 Close the response and release the connection.204 Automatically called if the response body is read to completion.205 """

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

lines 206–209why, one step back
206 if not self.is_closed:
207 self.is_closed = True208 if self.on_close is not None:209 await self.on_close()