Skip to content
Myr

models.py

This file

Path

httpcore/models.py

621 lines · 19.5 KiB · Python

Last changed by

Truckin' onTom Christiebefore adoption6b60d95

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

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Finessing interfaceTom Christiebefore adoptiond7619a9

line 17why, one step back
17from .status_codes import codes

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–54why, 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)5051 # Normalize schema and domain name.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–136why, 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 strictly133 # treats URLs with a fragment portion as not being absolute URLs,134 # but we want to treat them as such for the purposes of135 base_url = URL(base_url).copy_with(fragment=None)136 return URL(self.components.resolve_with(base_url.components))

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 137why, one step back
137

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 138–144why, one step back
138 def __hash__(self) -> int:
139 return hash(str(self))140141 def __eq__(self, other: typing.Any) -> bool:142 return isinstance(other, URL) and str(self) == str(other)143144 def __str__(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 146–153why, one step back
146
147 def __repr__(self) -> str:148 class_name = self.__class__.__name__149 url_str = str(self)150 return f"{class_name}({url_str!r})"151152153class Origin:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 166–169why, one step back
166 and self.port == other.port
167 )168169 def __hash__(self) -> int:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 192why, one step back
192 ]

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 196–224why, one step back
196 def encoding(self) -> str:
197 """198 Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be199 seen in the wild.200 """201 if self._encoding is None:202 for encoding in ["ascii", "utf-8"]:203 for key, value in self.raw:204 try:205 key.decode(encoding)206 value.decode(encoding)207 except UnicodeDecodeError:208 break209 else:210 # The else block runs if 'break' did not occur, meaning211 # all values fitted the encoding.212 self._encoding = encoding213 break214 else:215 # The ISO-8859-1 encoding covers all 256 code points in a byte,216 # so will never raise decode errors.217 self._encoding = "iso-8859-1"218 return self._encoding219220 @encoding.setter221 def encoding(self, value: str) -> None:222 self._encoding = value223224 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 258–261why, one step back
258 for item_key, item_value in self._list
259 if item_key == get_header_key260 ]261

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 271–279why, one step back
271 """
272 Return a single header value.273274 If there are multiple headers with the same key, then we concatenate275 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2276 """277 normalized_key = key.lower().encode(self.encoding)278279 items = []

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 296–314why, one step back
296
297 found_indexes = []298 for idx, (item_key, item_value) in enumerate(self._list):299 if item_key == set_key:300 found_indexes.append(idx)301302 for idx in reversed(found_indexes[1:]):303 del self._list[idx]304305 if found_indexes:306 idx = found_indexes[0]307 self._list[idx] = (set_key, set_value)308 else:309 self._list.append((set_key, set_value))310311 def __delitem__(self, key: str) -> None:312 """313 Remove the header `key`.314 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 327–344why, one step back
327 for header_key, header_value in self._list:
328 if header_key == get_header_key:329 return True330 return False331332 def __iter__(self) -> typing.Iterator[typing.Any]:333 return iter(self.keys())334335 def __len__(self) -> int:336 return len(self._list)337338 def __eq__(self, other: typing.Any) -> bool:339 if not isinstance(other, Headers):340 return False341 return sorted(self._list) == sorted(other._list)342343 def __repr__(self) -> str:344 class_name = self.__class__.__name__

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 390why, one step back
390 yield part

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 402–409why, one step back
402 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]
403404 has_host = "host" in self.headers405 has_content_length = (406 "content-length" in self.headers or "transfer-encoding" in self.headers407 )408 has_accept_encoding = "accept-encoding" in self.headers409

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 417–429why, one step back
417 auto_headers.append((b"content-length", content_length))
418 if not has_accept_encoding:419 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))420421 for item in reversed(auto_headers):422 self.headers.raw.insert(0, item)423424425class Response:426 def __init__(427 self,428 status_code: int,429 *,

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 430–432why, one step back
430 reason_phrase: str = None,
431 protocol: str = None,432 headers: HeaderTypes = None,

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 434–437why, one step back
434 on_close: typing.Callable = None,
435 request: Request = None,436 history: typing.List["Response"] = None,437 ):

Truckin' onTom Christiebefore adoption6b60d95

lines 438–442why, one step back
438 try:
439 # Use a StatusCode IntEnum if possible, for a nicer representation.440 self.status_code = codes(status_code)441 except ValueError:442 self.status_code = status_code

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 444–446why, one step back
444 self.protocol = protocol
445 self.headers = Headers(headers)446

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 449–450why, one step back
449 self.is_stream_consumed = True
450 self._raw_content = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 451why, one step back
451 else:

Response.contentTom Christiebefore adoption4c55113

lines 452–454why, one step back
452 self.is_closed = False
453 self.is_stream_consumed = False454 self._raw_stream = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 455why, one step back
455

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

response.next()Tom Christiebefore adoptiond652479

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 460–462why, one step back
460
461 @property462 def url(self) -> typing.Optional[URL]:

Clean up response interfaceTom Christiebefore adoption4d908d0

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 469–470why, one step back
469
470 @property

Response.contentTom Christiebefore adoption4c55113

lines 471–473why, one step back
471 def content(self) -> bytes:
472 if not hasattr(self, "_content"):473 if hasattr(self, "_raw_content"):

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 474–476why, one step back
474 content = self.decoder.decode(self._raw_content)
475 content += self.decoder.flush()476 self._content = content

Response.contentTom Christiebefore adoption4c55113

lines 477–479why, one step back
477 else:
478 raise ResponseNotRead()479 return self._content

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 480–515why, one step back
480
481 @property482 def text(self) -> str:483 if not hasattr(self, "_text"):484 content = self.content485 if not content:486 self._text = ""487 else:488 encoding = self.encoding489 self._text = content.decode(encoding, errors="replace")490 return self._text491492 @property493 def encoding(self) -> str:494 if not hasattr(self, "_encoding"):495 encoding = self.charset_encoding496 if encoding is None or not is_known_encoding(encoding):497 encoding = self.apparent_encoding498 if encoding is None or not is_known_encoding(encoding):499 encoding = "utf-8"500 self._encoding = encoding501 return self._encoding502503 @encoding.setter504 def encoding(self, value: str) -> None:505 self._encoding = value506507 @property508 def charset_encoding(self) -> typing.Optional[str]:509 """510 Return the encoding, as specified by the Content-Type header.511 """512 content_type = self.headers.get("Content-Type")513 if content_type is None:514 return None515

Truckin' onTom Christiebefore adoption0ca1c84

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

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

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

Truckin' onTom Christiebefore adoption0ca1c84

lines 524–527why, one step back
524 if media_type.startswith("text/"):
525 return "iso-8859-1"526527 return None

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 528–534why, one step back
528
529 @property530 def apparent_encoding(self) -> typing.Optional[str]:531 """532 Return the encoding, as it appears to autodetection.533 """534 return chardet.detect(self.content)["encoding"]

Response.contentTom Christiebefore adoption4c55113

lines 535–536why, one step back
535
536 @property

Clean up response interfaceTom Christiebefore adoption4d908d0

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

Response.contentTom Christiebefore adoption4c55113

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 545–547why, one step back
545 for value in values:
546 value = value.strip().lower()547 decoder_cls = SUPPORTED_DECODERS[value]

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 548–557why, one step back
548 decoders.append(decoder_cls())
549550 if len(decoders) == 1:551 self._decoder = decoders[0]552 elif len(decoders) > 1:553 self._decoder = MultiDecoder(decoders)554 else:555 self._decoder = IdentityDecoder()556557 return self._decoder

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 558–562why, one step back
558
559 async def read(self) -> bytes:560 """561 Read and return the response content.562 """

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 566–568why, one step back
566 content += part
567 self._content = content568 return self._content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 577–585why, one step back
577 else:
578 async for chunk in self.raw():579 yield self.decoder.decode(chunk)580 yield self.decoder.flush()581582 async def raw(self) -> typing.AsyncIterator[bytes]:583 """584 A byte-iterator over the raw response content.585 """

Response.contentTom Christiebefore adoption4c55113

lines 586–597why, one step back
586 if hasattr(self, "_raw_content"):
587 yield self._raw_content588 else:589 if self.is_stream_consumed:590 raise StreamConsumed()591 if self.is_closed:592 raise ResponseClosed()593594 self.is_stream_consumed = True595 async for part in self._raw_stream:596 yield part597 await self.close()

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 598–611why, one step back
598
599 async def close(self) -> None:600 """601 Close the response and release the connection.602 Automatically called if the response body is read to completion.603 """604 if not self.is_closed:605 self.is_closed = True606 if self.on_close is not None:607 await self.on_close()608609 @property610 def is_redirect(self) -> bool:611 return (

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 612–620why, one step back
612 self.status_code
613 in (614 codes.moved_permanently,615 codes.found,616 codes.see_other,617 codes.temporary_redirect,618 codes.permanent_redirect,619 )620 and "location" in self.headers

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 621why, one step back
621 )