Skip to content
Myr

models.py

This file

Path

httpcore/models.py

654 lines · 20.4 KiB · Python

Last changed by

Add `raise_for_status` to `Response`Matus Ferechbefore adoptionfb6d14f

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)

Add `raise_for_status` to `Response`Matus Ferechbefore adoptionfb6d14f

lines 17–23why, one step back
17from .exceptions import (
18 HttpError,19 InvalidURL,20 ResponseClosed,21 ResponseNotRead,22 StreamConsumed,23)

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 24–29why, one step back
24from .utils import (
25 get_reason_phrase,26 is_known_encoding,27 normalize_header_key,28 normalize_header_value,29)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 30why, one step back
30

Finessing interfaceTom Christiebefore adoptiond7619a9

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 32why, one step back
32

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 33–38why, one step back
33HeaderTypes = typing.Union[
34 "Headers",35 typing.Dict[typing.AnyStr, typing.AnyStr],36 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],37]38

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 40–41why, one step back
40
41

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 42why, one step back
42class URL:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 48–50why, one step back
48 else:
49 self.components = url.components50

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 51–56why, one step back
51 # Handle IDNA domain names.
52 if self.components.authority:53 idna_authority = self.components.authority.encode("idna").decode("ascii")54 if idna_authority != self.components.authority:55 self.components = self.components.copy_with(authority=idna_authority)56

Fix docstringsTom Christiebefore adoption8a227c1

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 58–60why, one step back
58 self.components = self.components.normalize()
5960 # Enforce absolute URLs by default.

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 61–66why, one step back
61 if not allow_relative:
62 if not self.scheme:63 raise InvalidURL("No scheme included in URL.")64 if self.scheme not in ("http", "https"):65 raise InvalidURL('URL scheme must be "http" or "https".')66 if not self.host:

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 68–70why, one step back
68
69 @property70 def scheme(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 72–73why, one step back
72
73 @property

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 76–77why, one step back
76
77 @property

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 80–85why, one step back
80
81 @property82 def port(self) -> int:83 port = self.components.port84 if port is None:85 return {"https": 443, "http": 80}[self.scheme]

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 87–88why, one step back
87
88 @property

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

lines 89–96why, one step back
89 def path(self) -> str:
90 return self.components.path or "/"9192 @property93 def query(self) -> str:94 return self.components.query or ""9596 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

lines 98–100why, one step back
98 path = self.path
99 if self.query:100 path += "?" + self.query

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 101–103why, one step back
101 return path
102103 @property

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

lines 104–107why, one step back
104 def fragment(self) -> str:
105 return self.components.fragment or ""106107 @property

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 109–111why, one step back
109 return self.components.scheme == "https"
110111 @property

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 122–123why, one step back
122
123 @property

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 124–127why, one step back
124 def is_relative_url(self) -> bool:
125 return not self.is_absolute_url126127 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 128–130why, one step back
128 def origin(self) -> "Origin":
129 return Origin(self)130

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 131–134why, one step back
131 def copy_with(self, **kwargs: typing.Any) -> "URL":
132 return URL(self.components.copy_with(**kwargs))133134 def resolve_with(self, base_url: URLTypes) -> "URL":

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 135–138why, one step back
135 """
136 Return an absolute URL, using base_url as the base.137 """138 # We drop any fragment portion, because RFC 3986 strictly

Fix docstringsTom Christiebefore adoption8a227c1

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 142why, one step back
142

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 143–149why, one step back
143 def __hash__(self) -> int:
144 return hash(str(self))145146 def __eq__(self, other: typing.Any) -> bool:147 return isinstance(other, URL) and str(self) == str(other)148149 def __str__(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 151–158why, one step back
151
152 def __repr__(self) -> str:153 class_name = self.__class__.__name__154 url_str = str(self)155 return f"{class_name}({url_str!r})"156157158class Origin:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 164–169why, one step back
164 self.port = url.port
165166 def __eq__(self, other: typing.Any) -> bool:167 return (168 isinstance(other, self.__class__)169 and self.is_ssl == other.is_ssl

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 171–174why, one step back
171 and self.port == other.port
172 )173174 def __hash__(self) -> int:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 176–182why, one step back
176
177178class Headers(typing.MutableMapping[str, str]):179 """180 A case-insensitive multidict.181 """182

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 184–189why, one step back
184 if headers is None:
185 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]186 elif isinstance(headers, Headers):187 self._list = list(headers.raw)188 elif isinstance(headers, dict):189 self._list = [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 191–194why, one step back
191 for k, v in headers.items()
192 ]193 else:194 self._list = [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 197why, one step back
197 ]

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 199–200why, one step back
199
200 @property

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 201–229why, one step back
201 def encoding(self) -> str:
202 """203 Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be204 seen in the wild.205 """206 if self._encoding is None:207 for encoding in ["ascii", "utf-8"]:208 for key, value in self.raw:209 try:210 key.decode(encoding)211 value.decode(encoding)212 except UnicodeDecodeError:213 break214 else:215 # The else block runs if 'break' did not occur, meaning216 # all values fitted the encoding.217 self._encoding = encoding218 break219 else:220 # The ISO-8859-1 encoding covers all 256 code points in a byte,221 # so will never raise decode errors.222 self._encoding = "iso-8859-1"223 return self._encoding224225 @encoding.setter226 def encoding(self, value: str) -> None:227 self._encoding = value228229 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 231–234why, one step back
231 """
232 Returns a list of the raw header items, as byte pairs.233 May be mutated in-place.234 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 242–244why, one step back
242
243 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore244 return [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 246–254why, one step back
246 for key, value in self._list
247 ]248249 def get(self, key: str, default: typing.Any = None) -> typing.Any:250 try:251 return self[key]252 except KeyError:253 return default254

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 256–262why, one step back
256 """
257 Return multiple header values.258 """259 get_header_key = key.lower().encode(self.encoding)260261 values = [262 item_value.decode(self.encoding)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 263–266why, one step back
263 for item_key, item_value in self._list
264 if item_key == get_header_key265 ]266

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 267–274why, one step back
267 if not split_commas:
268 return values269270 split_values = []271 for value in values:272 split_values.extend([item.strip() for item in value.split(",")])273 return split_values274

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 286–291why, one step back
286 if header_key == normalized_key:
287 items.append(header_value.decode(self.encoding))288289 if items:290 return ", ".join(items)291

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 292–298why, one step back
292 raise KeyError(key)
293294 def __setitem__(self, key: str, value: str) -> None:295 """296 Set the header `key` to `value`, removing any duplicate entries.297 Retains insertion order.298 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 301–319why, one step back
301
302 found_indexes = []303 for idx, (item_key, item_value) in enumerate(self._list):304 if item_key == set_key:305 found_indexes.append(idx)306307 for idx in reversed(found_indexes[1:]):308 del self._list[idx]309310 if found_indexes:311 idx = found_indexes[0]312 self._list[idx] = (set_key, set_value)313 else:314 self._list.append((set_key, set_value))315316 def __delitem__(self, key: str) -> None:317 """318 Remove the header `key`.319 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 321–330why, one step back
321
322 pop_indexes = []323 for idx, (item_key, item_value) in enumerate(self._list):324 if item_key == del_key:325 pop_indexes.append(idx)326327 for idx in reversed(pop_indexes):328 del self._list[idx]329330 def __contains__(self, key: typing.Any) -> bool:

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 332–349why, one step back
332 for header_key, header_value in self._list:
333 if header_key == get_header_key:334 return True335 return False336337 def __iter__(self) -> typing.Iterator[typing.Any]:338 return iter(self.keys())339340 def __len__(self) -> int:341 return len(self._list)342343 def __eq__(self, other: typing.Any) -> bool:344 if not isinstance(other, Headers):345 return False346 return sorted(self._list) == sorted(other._list)347348 def __repr__(self) -> str:349 class_name = self.__class__.__name__

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 350–354why, one step back
350
351 encoding_str = ""352 if self.encoding != "ascii":353 encoding_str = f", encoding={self.encoding!r}"354

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 360–368why, one step back
360
361362class Request:363 def __init__(364 self,365 method: str,366 url: typing.Union[str, URL],367 *,368 headers: HeaderTypes = None,

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 370–372why, one step back
370 ):
371 self.method = method.upper()372 self.url = URL(url) if isinstance(url, str) else url

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 376–377why, one step back
376 else:
377 self.is_streaming = True

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 379–384why, one step back
379 self.headers = Headers(headers)
380381 async def read(self) -> bytes:382 """383 Read and return the response content.384 """

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 388–390why, one step back
388 content += part
389 self.content = content390 return self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 395why, one step back
395 yield part

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 396–397why, one step back
396 elif self.content:
397 yield self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 407–414why, one step back
407 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]
408409 has_host = "host" in self.headers410 has_content_length = (411 "content-length" in self.headers or "transfer-encoding" in self.headers412 )413 has_accept_encoding = "accept-encoding" in self.headers414

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 422–428why, one step back
422 auto_headers.append((b"content-length", content_length))
423 if not has_accept_encoding:424 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))425426 for item in reversed(auto_headers):427 self.headers.raw.insert(0, item)428

Still truckin' onTom Christiebefore adoption6cb5c0d

lines 429–432why, one step back
429 def __repr__(self) -> str:
430 class_name = self.__class__.__name__431 url = str(self.url)432 return f"<{class_name}({self.method}, {url})>"

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 433why, one step back
433

Still truckin' onTom Christiebefore adoption6cb5c0d

line 434why, one step back
434

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 435–439why, one step back
435class Response:
436 def __init__(437 self,438 status_code: int,439 *,

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 440–442why, one step back
440 reason_phrase: str = None,
441 protocol: str = None,442 headers: HeaderTypes = None,

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 444–447why, one step back
444 on_close: typing.Callable = None,
445 request: Request = None,446 history: typing.List["Response"] = None,447 ):

Truckin' onTom Christiebefore adoption6b60d95

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

Still truckin' onTom Christiebefore adoption6cb5c0d

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

Truckin' onTom Christiebefore adoption6b60d95

lines 451–452why, one step back
451 except ValueError:
452 self.status_code = status_code

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 454–456why, one step back
454 self.protocol = protocol
455 self.headers = Headers(headers)456

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 459–460why, one step back
459 self.is_stream_consumed = True
460 self._raw_content = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 461why, one step back
461 else:

Response.contentTom Christiebefore adoption4c55113

lines 462–464why, one step back
462 self.is_closed = False
463 self.is_stream_consumed = False464 self._raw_stream = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 465why, one step back
465

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

response.next()Tom Christiebefore adoptiond652479

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 470–472why, one step back
470
471 @property472 def url(self) -> typing.Optional[URL]:

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 473–477why, one step back
473 """
474 Returns the URL for which the request was made.475476 Requires that `request` was provided when instantiating the response.477 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 479–480why, one step back
479
480 @property

Response.contentTom Christiebefore adoption4c55113

lines 481–483why, one step back
481 def content(self) -> bytes:
482 if not hasattr(self, "_content"):483 if hasattr(self, "_raw_content"):

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 484–486why, one step back
484 content = self.decoder.decode(self._raw_content)
485 content += self.decoder.flush()486 self._content = content

Response.contentTom Christiebefore adoption4c55113

lines 487–489why, one step back
487 else:
488 raise ResponseNotRead()489 return self._content

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 490–525why, one step back
490
491 @property492 def text(self) -> str:493 if not hasattr(self, "_text"):494 content = self.content495 if not content:496 self._text = ""497 else:498 encoding = self.encoding499 self._text = content.decode(encoding, errors="replace")500 return self._text501502 @property503 def encoding(self) -> str:504 if not hasattr(self, "_encoding"):505 encoding = self.charset_encoding506 if encoding is None or not is_known_encoding(encoding):507 encoding = self.apparent_encoding508 if encoding is None or not is_known_encoding(encoding):509 encoding = "utf-8"510 self._encoding = encoding511 return self._encoding512513 @encoding.setter514 def encoding(self, value: str) -> None:515 self._encoding = value516517 @property518 def charset_encoding(self) -> typing.Optional[str]:519 """520 Return the encoding, as specified by the Content-Type header.521 """522 content_type = self.headers.get("Content-Type")523 if content_type is None:524 return None525

Truckin' onTom Christiebefore adoption0ca1c84

lines 526–530why, one step back
526 parsed = cgi.parse_header(content_type)
527 media_type, params = parsed[0], parsed[-1]528 if "charset" in params:529 return params["charset"].strip("'\"")530

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

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

Truckin' onTom Christiebefore adoption0ca1c84

lines 534–537why, one step back
534 if media_type.startswith("text/"):
535 return "iso-8859-1"536537 return None

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 538–544why, one step back
538
539 @property540 def apparent_encoding(self) -> typing.Optional[str]:541 """542 Return the encoding, as it appears to autodetection.543 """544 return chardet.detect(self.content)["encoding"]

Response.contentTom Christiebefore adoption4c55113

lines 545–546why, one step back
545
546 @property

Clean up response interfaceTom Christiebefore adoption4d908d0

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

Response.contentTom Christiebefore adoption4c55113

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 555–557why, one step back
555 for value in values:
556 value = value.strip().lower()557 decoder_cls = SUPPORTED_DECODERS[value]

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 558–567why, one step back
558 decoders.append(decoder_cls())
559560 if len(decoders) == 1:561 self._decoder = decoders[0]562 elif len(decoders) > 1:563 self._decoder = MultiDecoder(decoders)564 else:565 self._decoder = IdentityDecoder()566567 return self._decoder

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 568–572why, one step back
568
569 async def read(self) -> bytes:570 """571 Read and return the response content.572 """

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 576–578why, one step back
576 content += part
577 self._content = content578 return self._content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 579–584why, one step back
579
580 async def stream(self) -> typing.AsyncIterator[bytes]:581 """582 A byte-iterator over the decoded response content.583 This allows us to handle gzip, deflate, and brotli encoded responses.584 """

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 596–607why, one step back
596 if hasattr(self, "_raw_content"):
597 yield self._raw_content598 else:599 if self.is_stream_consumed:600 raise StreamConsumed()601 if self.is_closed:602 raise ResponseClosed()603604 self.is_stream_consumed = True605 async for part in self._raw_stream:606 yield part607 await self.close()

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 608–621why, one step back
608
609 async def close(self) -> None:610 """611 Close the response and release the connection.612 Automatically called if the response body is read to completion.613 """614 if not self.is_closed:615 self.is_closed = True616 if self.on_close is not None:617 await self.on_close()618619 @property620 def is_redirect(self) -> bool:621 return (

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 622–630why, one step back
622 self.status_code
623 in (624 codes.moved_permanently,625 codes.found,626 codes.see_other,627 codes.temporary_redirect,628 codes.permanent_redirect,629 )630 and "location" in self.headers

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 631why, one step back
631 )

Still truckin' onTom Christiebefore adoption6cb5c0d

lines 632–635why, one step back
632
633 def __repr__(self) -> str:634 class_name = self.__class__.__name__635 return f"<{class_name}(status_code={self.status_code})>"

Add `raise_for_status` to `Response`Matus Ferechbefore adoptionfb6d14f

lines 636–654why, one step back
636
637 def raise_for_status(self) -> None:638 """639 Raise the `HttpError` if one occurred.640 """641 message = (642 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"643 "For more information check: https://httpstatuses.com/{0.status_code}"644 )645646 if 400 <= self.status_code < 500:647 message = message.format(self, error_type="Client Error")648 elif 500 <= self.status_code < 600:649 message = message.format(self, error_type="Server Error")650 else:651 message = ""652653 if message:654 raise HttpError(message)