Skip to content
Myr

models.py

This file

Path

httpcore/models.py

629 lines · 19.7 KiB · Python

Last changed by

Fix docstringsTom Christiebefore adoption8a227c1

History of this file

Take it

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

line 1why, one step back
1import cgi

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 2–3why, one step back
2import typing
3

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

line 4why, one step back
4import chardet

Add idna support. More tests.Tom Christiebefore adoptionb948798

line 5why, one step back
5import idna

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 6why, one step back
6import rfc3986

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

line 7why, one step back
7

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Reorganise structureTom Christiebefore adoption0c6f618

line 9why, one step back
9from .constants import codes

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 10–16why, one step back
10from .decoders import (
11 ACCEPT_ENCODING,12 SUPPORTED_DECODERS,13 Decoder,14 IdentityDecoder,15 MultiDecoder,16)

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 17why, one step back
17from .exceptions import InvalidURL, ResponseClosed, ResponseNotRead, StreamConsumed

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 18–23why, one step back
18from .utils import (
19 get_reason_phrase,20 is_known_encoding,21 normalize_header_key,22 normalize_header_value,23)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 24why, one step back
24

Finessing interfaceTom Christiebefore adoptiond7619a9

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 26why, one step back
26

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 27–32why, one step back
27HeaderTypes = typing.Union[
28 "Headers",29 typing.Dict[typing.AnyStr, typing.AnyStr],30 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],31]32

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

line 33why, one step back
33ByteOrByteStream = typing.Union[bytes, typing.AsyncIterator[bytes]]

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 34–35why, one step back
34
35

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 36why, one step back
36class URL:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 37why, one step back
37 def __init__(self, url: URLTypes, allow_relative: bool = False) -> None:

Add idna support. More tests.Tom Christiebefore adoptionb948798

line 38why, one step back
38 if isinstance(url, rfc3986.uri.URIReference):

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 39why, one step back
39 self.components = url

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 40–41why, one step back
40 elif isinstance(url, str):
41 self.components = rfc3986.api.uri_reference(url)

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 42–44why, one step back
42 else:
43 self.components = url.components44

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 45–50why, one step back
45 # Handle IDNA domain names.
46 if self.components.authority:47 idna_authority = self.components.authority.encode("idna").decode("ascii")48 if idna_authority != self.components.authority:49 self.components = self.components.copy_with(authority=idna_authority)50

Fix docstringsTom Christiebefore adoption8a227c1

line 51why, one step back
51 # Normalize scheme and domain name.

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 52–54why, one step back
52 self.components = self.components.normalize()
5354 # Enforce absolute URLs by default.

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 55–60why, one step back
55 if not allow_relative:
56 if not self.scheme:57 raise InvalidURL("No scheme included in URL.")58 if self.scheme not in ("http", "https"):59 raise InvalidURL('URL scheme must be "http" or "https".')60 if not self.host:

Add idna support. More tests.Tom Christiebefore adoptionb948798

line 61why, one step back
61 raise InvalidURL("No host included in URL.")

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 62–64why, one step back
62
63 @property64 def scheme(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 65why, one step back
65 return self.components.scheme or ""

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 66–67why, one step back
66
67 @property

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 68–69why, one step back
68 def authority(self) -> str:
69 return self.components.authority or ""

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 70–71why, one step back
70
71 @property

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 72–73why, one step back
72 def host(self) -> str:
73 return self.components.host or ""

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 74–79why, one step back
74
75 @property76 def port(self) -> int:77 port = self.components.port78 if port is None:79 return {"https": 443, "http": 80}[self.scheme]

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

line 80why, one step back
80 return int(port)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 81–82why, one step back
81
82 @property

Media types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb

lines 83–90why, one step back
83 def path(self) -> str:
84 return self.components.path or "/"8586 @property87 def query(self) -> str:88 return self.components.query or ""8990 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 91why, one step back
91 def full_path(self) -> str:

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

lines 92–94why, one step back
92 path = self.path
93 if self.query:94 path += "?" + self.query

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 95–97why, one step back
95 return path
9697 @property

Media types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb

lines 98–101why, one step back
98 def fragment(self) -> str:
99 return self.components.fragment or ""100101 @property

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

line 102why, one step back
102 def is_ssl(self) -> bool:

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 103–105why, one step back
103 return self.components.scheme == "https"
104105 @property

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 106–115why, one step back
106 def is_absolute_url(self) -> bool:
107 """108 Return `True` for absolute URLs such as 'http://example.com/path',109 and `False` for relative URLs such as '/path'.110 """111 # We don't use rfc3986's `is_absolute` because it treats112 # URLs with a fragment portion as not absolute.113 # What we actually care about is if the URL provides114 # a scheme and hostname to which connections should be made.115 return self.components.scheme and self.components.host

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 116–117why, one step back
116
117 @property

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 118–121why, one step back
118 def is_relative_url(self) -> bool:
119 return not self.is_absolute_url120121 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 122–124why, one step back
122 def origin(self) -> "Origin":
123 return Origin(self)124

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 125–128why, one step back
125 def copy_with(self, **kwargs: typing.Any) -> "URL":
126 return URL(self.components.copy_with(**kwargs))127128 def resolve_with(self, base_url: URLTypes) -> "URL":

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 129–132why, one step back
129 """
130 Return an absolute URL, using base_url as the base.131 """132 # We drop any fragment portion, because RFC 3986 strictly

Fix docstringsTom Christiebefore adoption8a227c1

line 133why, one step back
133 # treats URLs with a fragment portion as not being absolute URLs.

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 134–135why, one step back
134 base_url = URL(base_url).copy_with(fragment=None)
135 return URL(self.components.resolve_with(base_url.components))

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 136why, one step back
136

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 137–143why, one step back
137 def __hash__(self) -> int:
138 return hash(str(self))139140 def __eq__(self, other: typing.Any) -> bool:141 return isinstance(other, URL) and str(self) == str(other)142143 def __str__(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 144why, one step back
144 return self.components.unsplit()

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 145–152why, one step back
145
146 def __repr__(self) -> str:147 class_name = self.__class__.__name__148 url_str = str(self)149 return f"{class_name}({url_str!r})"150151152class Origin:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 153–154why, one step back
153 def __init__(self, url: URLTypes) -> None:
154 if not isinstance(url, URL):

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 155why, one step back
155 url = URL(url)

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

line 156why, one step back
156 self.is_ssl = url.is_ssl

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 157why, one step back
157 self.host = url.host

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 158–163why, one step back
158 self.port = url.port
159160 def __eq__(self, other: typing.Any) -> bool:161 return (162 isinstance(other, self.__class__)163 and self.is_ssl == other.is_ssl

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 164why, one step back
164 and self.host == other.host

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 165–168why, one step back
165 and self.port == other.port
166 )167168 def __hash__(self) -> int:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 169why, one step back
169 return hash((self.is_ssl, self.host, self.port))

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 170–176why, one step back
170
171172class Headers(typing.MutableMapping[str, str]):173 """174 A case-insensitive multidict.175 """176

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

line 177why, one step back
177 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 178–183why, one step back
178 if headers is None:
179 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]180 elif isinstance(headers, Headers):181 self._list = list(headers.raw)182 elif isinstance(headers, dict):183 self._list = [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

line 184why, one step back
184 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 185–188why, one step back
185 for k, v in headers.items()
186 ]187 else:188 self._list = [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 189–190why, one step back
189 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))
190 for k, v in headers

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 191why, one step back
191 ]

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

line 192why, one step back
192 self._encoding = encoding

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 193–194why, one step back
193
194 @property

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 195–223why, one step back
195 def encoding(self) -> str:
196 """197 Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be198 seen in the wild.199 """200 if self._encoding is None:201 for encoding in ["ascii", "utf-8"]:202 for key, value in self.raw:203 try:204 key.decode(encoding)205 value.decode(encoding)206 except UnicodeDecodeError:207 break208 else:209 # The else block runs if 'break' did not occur, meaning210 # all values fitted the encoding.211 self._encoding = encoding212 break213 else:214 # The ISO-8859-1 encoding covers all 256 code points in a byte,215 # so will never raise decode errors.216 self._encoding = "iso-8859-1"217 return self._encoding218219 @encoding.setter220 def encoding(self, value: str) -> None:221 self._encoding = value222223 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 224why, one step back
224 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 225–228why, one step back
225 """
226 Returns a list of the raw header items, as byte pairs.227 May be mutated in-place.228 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 229–231why, one step back
229 return self._list
230231 def keys(self) -> typing.List[str]: # type: ignore

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

line 232why, one step back
232 return [key.decode(self.encoding) for key, value in self._list]

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 233–234why, one step back
233
234 def values(self) -> typing.List[str]: # type: ignore

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

line 235why, one step back
235 return [value.decode(self.encoding) for key, value in self._list]

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 236–238why, one step back
236
237 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore238 return [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

line 239why, one step back
239 (key.decode(self.encoding), value.decode(self.encoding))

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 240–248why, one step back
240 for key, value in self._list
241 ]242243 def get(self, key: str, default: typing.Any = None) -> typing.Any:244 try:245 return self[key]246 except KeyError:247 return default248

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

line 249why, one step back
249 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 250–256why, one step back
250 """
251 Return multiple header values.252 """253 get_header_key = key.lower().encode(self.encoding)254255 values = [256 item_value.decode(self.encoding)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 257–260why, one step back
257 for item_key, item_value in self._list
258 if item_key == get_header_key259 ]260

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 261–268why, one step back
261 if not split_commas:
262 return values263264 split_values = []265 for value in values:266 split_values.extend([item.strip() for item in value.split(",")])267 return split_values268

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 269why, one step back
269 def __getitem__(self, key: str) -> str:

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 270–278why, one step back
270 """
271 Return a single header value.272273 If there are multiple headers with the same key, then we concatenate274 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2275 """276 normalized_key = key.lower().encode(self.encoding)277278 items = []

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 279why, one step back
279 for header_key, header_value in self._list:

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 280–285why, one step back
280 if header_key == normalized_key:
281 items.append(header_value.decode(self.encoding))282283 if items:284 return ", ".join(items)285

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 286–292why, one step back
286 raise KeyError(key)
287288 def __setitem__(self, key: str, value: str) -> None:289 """290 Set the header `key` to `value`, removing any duplicate entries.291 Retains insertion order.292 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 293–294why, one step back
293 set_key = key.lower().encode(self.encoding)
294 set_value = value.encode(self.encoding)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 295–313why, one step back
295
296 found_indexes = []297 for idx, (item_key, item_value) in enumerate(self._list):298 if item_key == set_key:299 found_indexes.append(idx)300301 for idx in reversed(found_indexes[1:]):302 del self._list[idx]303304 if found_indexes:305 idx = found_indexes[0]306 self._list[idx] = (set_key, set_value)307 else:308 self._list.append((set_key, set_value))309310 def __delitem__(self, key: str) -> None:311 """312 Remove the header `key`.313 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

line 314why, one step back
314 del_key = key.lower().encode(self.encoding)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 315–324why, one step back
315
316 pop_indexes = []317 for idx, (item_key, item_value) in enumerate(self._list):318 if item_key == del_key:319 pop_indexes.append(idx)320321 for idx in reversed(pop_indexes):322 del self._list[idx]323324 def __contains__(self, key: typing.Any) -> bool:

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

line 325why, one step back
325 get_header_key = key.lower().encode(self.encoding)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 326–343why, one step back
326 for header_key, header_value in self._list:
327 if header_key == get_header_key:328 return True329 return False330331 def __iter__(self) -> typing.Iterator[typing.Any]:332 return iter(self.keys())333334 def __len__(self) -> int:335 return len(self._list)336337 def __eq__(self, other: typing.Any) -> bool:338 if not isinstance(other, Headers):339 return False340 return sorted(self._list) == sorted(other._list)341342 def __repr__(self) -> str:343 class_name = self.__class__.__name__

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 344–348why, one step back
344
345 encoding_str = ""346 if self.encoding != "ascii":347 encoding_str = f", encoding={self.encoding!r}"348

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 349–350why, one step back
349 as_dict = dict(self.items())
350 if len(as_dict) == len(self):

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 351–353why, one step back
351 return f"{class_name}({as_dict!r}{encoding_str})"
352 as_list = self.items()353 return f"{class_name}({as_list!r}{encoding_str})"

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 354–362why, one step back
354
355356class Request:357 def __init__(358 self,359 method: str,360 url: typing.Union[str, URL],361 *,362 headers: HeaderTypes = None,

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

line 363why, one step back
363 content: ByteOrByteStream = b"",

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 364–366why, one step back
364 ):
365 self.method = method.upper()366 self.url = URL(url) if isinstance(url, str) else url

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

line 367why, one step back
367 if isinstance(content, bytes):

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 368why, one step back
368 self.is_streaming = False

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

line 369why, one step back
369 self.content = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 370–371why, one step back
370 else:
371 self.is_streaming = True

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

line 372why, one step back
372 self.content_aiter = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 373–378why, one step back
373 self.headers = Headers(headers)
374375 async def read(self) -> bytes:376 """377 Read and return the response content.378 """

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 379–380why, one step back
379 if not hasattr(self, "content"):
380 content = b""

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 381why, one step back
381 async for part in self.stream():

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 382–384why, one step back
382 content += part
383 self.content = content384 return self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 385–387why, one step back
385
386 async def stream(self) -> typing.AsyncIterator[bytes]:387 if self.is_streaming:

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

line 388why, one step back
388 async for part in self.content_aiter:

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 389why, one step back
389 yield part

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 390–391why, one step back
390 elif self.content:
391 yield self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 392–393why, one step back
392
393 def prepare(self) -> None:

Response.contentTom Christiebefore adoption4c55113

lines 394–400why, one step back
394 """
395 Adds in any default headers. When using the `Client`, this will396 end up being called into by the `prepare_request()` stage.397398 You can omit this behavior by calling `Client.send()` with an399 explicitly built `Request` instance.400 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 401–408why, one step back
401 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]
402403 has_host = "host" in self.headers404 has_content_length = (405 "content-length" in self.headers or "transfer-encoding" in self.headers406 )407 has_accept_encoding = "accept-encoding" in self.headers408

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 409–410why, one step back
409 if not has_host and self.url.authority:
410 auto_headers.append((b"host", self.url.authority.encode("ascii")))

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 411–413why, one step back
411 if not has_content_length:
412 if self.is_streaming:413 auto_headers.append((b"transfer-encoding", b"chunked"))

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 414–415why, one step back
414 elif self.content:
415 content_length = str(len(self.content)).encode()

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 416–422why, one step back
416 auto_headers.append((b"content-length", content_length))
417 if not has_accept_encoding:418 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))419420 for item in reversed(auto_headers):421 self.headers.raw.insert(0, item)422

Still truckin' onTom Christiebefore adoption6cb5c0d

lines 423–426why, one step back
423 def __repr__(self) -> str:
424 class_name = self.__class__.__name__425 url = str(self.url)426 return f"<{class_name}({self.method}, {url})>"

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 427why, one step back
427

Still truckin' onTom Christiebefore adoption6cb5c0d

line 428why, one step back
428

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 429–433why, one step back
429class Response:
430 def __init__(431 self,432 status_code: int,433 *,

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 434–436why, one step back
434 reason_phrase: str = None,
435 protocol: str = None,436 headers: HeaderTypes = None,

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

line 437why, one step back
437 content: ByteOrByteStream = b"",

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 438–441why, one step back
438 on_close: typing.Callable = None,
439 request: Request = None,440 history: typing.List["Response"] = None,441 ):

Truckin' onTom Christiebefore adoption6b60d95

lines 442–443why, one step back
442 try:
443 # Use a StatusCode IntEnum if possible, for a nicer representation.

Still truckin' onTom Christiebefore adoption6cb5c0d

line 444why, one step back
444 self.status_code = codes(status_code) # type: int

Truckin' onTom Christiebefore adoption6b60d95

lines 445–446why, one step back
445 except ValueError:
446 self.status_code = status_code

Response.contentTom Christiebefore adoption4c55113

line 447why, one step back
447 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 448–450why, one step back
448 self.protocol = protocol
449 self.headers = Headers(headers)450

Response.contentTom Christiebefore adoption4c55113

line 451why, one step back
451 if isinstance(content, bytes):

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 452why, one step back
452 self.is_closed = True

Response.contentTom Christiebefore adoption4c55113

lines 453–454why, one step back
453 self.is_stream_consumed = True
454 self._raw_content = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 455why, one step back
455 else:

Response.contentTom Christiebefore adoption4c55113

lines 456–458why, one step back
456 self.is_closed = False
457 self.is_stream_consumed = False458 self._raw_stream = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 459why, one step back
459

Response.contentTom Christiebefore adoption4c55113

line 460why, one step back
460 self.on_close = on_close

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 461–462why, one step back
461 self.request = request
462 self.history = [] if history is None else list(history)

response.next()Tom Christiebefore adoptiond652479

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 464–466why, one step back
464
465 @property466 def url(self) -> typing.Optional[URL]:

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 467–471why, one step back
467 """
468 Returns the URL for which the request was made.469470 Requires that `request` was provided when instantiating the response.471 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 472why, one step back
472 return None if self.request is None else self.request.url

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 473–474why, one step back
473
474 @property

Response.contentTom Christiebefore adoption4c55113

lines 475–477why, one step back
475 def content(self) -> bytes:
476 if not hasattr(self, "_content"):477 if hasattr(self, "_raw_content"):

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 478–480why, one step back
478 content = self.decoder.decode(self._raw_content)
479 content += self.decoder.flush()480 self._content = content

Response.contentTom Christiebefore adoption4c55113

lines 481–483why, one step back
481 else:
482 raise ResponseNotRead()483 return self._content

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 484–519why, one step back
484
485 @property486 def text(self) -> str:487 if not hasattr(self, "_text"):488 content = self.content489 if not content:490 self._text = ""491 else:492 encoding = self.encoding493 self._text = content.decode(encoding, errors="replace")494 return self._text495496 @property497 def encoding(self) -> str:498 if not hasattr(self, "_encoding"):499 encoding = self.charset_encoding500 if encoding is None or not is_known_encoding(encoding):501 encoding = self.apparent_encoding502 if encoding is None or not is_known_encoding(encoding):503 encoding = "utf-8"504 self._encoding = encoding505 return self._encoding506507 @encoding.setter508 def encoding(self, value: str) -> None:509 self._encoding = value510511 @property512 def charset_encoding(self) -> typing.Optional[str]:513 """514 Return the encoding, as specified by the Content-Type header.515 """516 content_type = self.headers.get("Content-Type")517 if content_type is None:518 return None519

Truckin' onTom Christiebefore adoption0ca1c84

lines 520–524why, one step back
520 parsed = cgi.parse_header(content_type)
521 media_type, params = parsed[0], parsed[-1]522 if "charset" in params:523 return params["charset"].strip("'\"")524

Media types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb

lines 525–527why, one step back
525 # RFC 2616 specifies that 'iso-8859-1' should be used as the default
526 # for 'text/*' media types, if no charset is provided.527 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1

Truckin' onTom Christiebefore adoption0ca1c84

lines 528–531why, one step back
528 if media_type.startswith("text/"):
529 return "iso-8859-1"530531 return None

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 532–538why, one step back
532
533 @property534 def apparent_encoding(self) -> typing.Optional[str]:535 """536 Return the encoding, as it appears to autodetection.537 """538 return chardet.detect(self.content)["encoding"]

Response.contentTom Christiebefore adoption4c55113

lines 539–540why, one step back
539
540 @property

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 541–547why, one step back
541 def decoder(self) -> Decoder:
542 """543 Returns a decoder instance which can be used to decode the raw byte544 content, depending on the Content-Encoding used in the response.545 """546 if not hasattr(self, "_decoder"):547 decoders = [] # type: typing.List[Decoder]

Response.contentTom Christiebefore adoption4c55113

line 548why, one step back
548 values = self.headers.getlist("content-encoding", split_commas=True)

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 549–551why, one step back
549 for value in values:
550 value = value.strip().lower()551 decoder_cls = SUPPORTED_DECODERS[value]

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 552–561why, one step back
552 decoders.append(decoder_cls())
553554 if len(decoders) == 1:555 self._decoder = decoders[0]556 elif len(decoders) > 1:557 self._decoder = MultiDecoder(decoders)558 else:559 self._decoder = IdentityDecoder()560561 return self._decoder

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 562–566why, one step back
562
563 async def read(self) -> bytes:564 """565 Read and return the response content.566 """

Response.contentTom Christiebefore adoption4c55113

lines 567–568why, one step back
567 if not hasattr(self, "_content"):
568 content = b""

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 569why, one step back
569 async for part in self.stream():

Response.contentTom Christiebefore adoption4c55113

lines 570–572why, one step back
570 content += part
571 self._content = content572 return self._content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 573–578why, one step back
573
574 async def stream(self) -> typing.AsyncIterator[bytes]:575 """576 A byte-iterator over the decoded response content.577 This allows us to handle gzip, deflate, and brotli encoded responses.578 """

Response.contentTom Christiebefore adoption4c55113

lines 579–580why, one step back
579 if hasattr(self, "_content"):
580 yield self._content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 581–589why, one step back
581 else:
582 async for chunk in self.raw():583 yield self.decoder.decode(chunk)584 yield self.decoder.flush()585586 async def raw(self) -> typing.AsyncIterator[bytes]:587 """588 A byte-iterator over the raw response content.589 """

Response.contentTom Christiebefore adoption4c55113

lines 590–601why, one step back
590 if hasattr(self, "_raw_content"):
591 yield self._raw_content592 else:593 if self.is_stream_consumed:594 raise StreamConsumed()595 if self.is_closed:596 raise ResponseClosed()597598 self.is_stream_consumed = True599 async for part in self._raw_stream:600 yield part601 await self.close()

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 602–615why, one step back
602
603 async def close(self) -> None:604 """605 Close the response and release the connection.606 Automatically called if the response body is read to completion.607 """608 if not self.is_closed:609 self.is_closed = True610 if self.on_close is not None:611 await self.on_close()612613 @property614 def is_redirect(self) -> bool:615 return (

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 616–624why, one step back
616 self.status_code
617 in (618 codes.moved_permanently,619 codes.found,620 codes.see_other,621 codes.temporary_redirect,622 codes.permanent_redirect,623 )624 and "location" in self.headers

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 625why, one step back
625 )

Still truckin' onTom Christiebefore adoption6cb5c0d

lines 626–629why, one step back
626
627 def __repr__(self) -> str:628 class_name = self.__class__.__name__629 return f"<{class_name}(status_code={self.status_code})>"