Skip to content
Myr

models.py

This file

Path

httpcore/models.py

746 lines · 23.1 KiB · Python

Last changed by

Improve class __repr__Tom Christiebefore adoption666d5a8

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

line 2why, one step back
2import typing

Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425

line 3why, one step back
3from urllib.parse import parse_qsl, urlencode

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 4why, one step back
4

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

line 5why, one step back
5import chardet

Add idna support. More tests.Tom Christiebefore adoptionb948798

line 6why, one step back
6import idna

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 7why, one step back
7import rfc3986

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

line 8why, one step back
8

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Reorganise structureTom Christiebefore adoption0c6f618

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30

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

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 31why, one step back
31

Finessing interfaceTom Christiebefore adoptiond7619a9

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 33why, one step back
33

Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425

lines 34–40why, one step back
34QueryParamTypes = typing.Union[
35 "QueryParams",36 typing.Mapping[str, str],37 typing.List[typing.Tuple[typing.Any, typing.Any]],38 str,39]40

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 41–46why, one step back
41HeaderTypes = typing.Union[
42 "Headers",43 typing.Dict[typing.AnyStr, typing.AnyStr],44 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],45]46

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 48–49why, one step back
48
49

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 50why, one step back
50class URL:

Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425

lines 51–56why, one step back
51 def __init__(
52 self,53 url: URLTypes,54 allow_relative: bool = False,55 query_params: QueryParamTypes = None,56 ) -> None:

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 61–63why, one step back
61 else:
62 self.components = url.components63

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 64–69why, one step back
64 # Handle IDNA domain names.
65 if self.components.authority:66 idna_authority = self.components.authority.encode("idna").decode("ascii")67 if idna_authority != self.components.authority:68 self.components = self.components.copy_with(authority=idna_authority)69

Fix docstringsTom Christiebefore adoption8a227c1

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 71–72why, one step back
71 self.components = self.components.normalize()
72

Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425

lines 73–77why, one step back
73 # Add any query parameters.
74 if query_params:75 query_string = str(QueryParams(query_params))76 self.components = self.components.copy_with(query=query_string)77

Add idna support. More tests.Tom Christiebefore adoptionb948798

line 78why, one step back
78 # Enforce absolute URLs by default.

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 79–84why, one step back
79 if not allow_relative:
80 if not self.scheme:81 raise InvalidURL("No scheme included in URL.")82 if self.scheme not in ("http", "https"):83 raise InvalidURL('URL scheme must be "http" or "https".')84 if not self.host:

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 86–88why, one step back
86
87 @property88 def scheme(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 90–91why, one step back
90
91 @property

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 94–95why, one step back
94
95 @property

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 98–103why, one step back
98
99 @property100 def port(self) -> int:101 port = self.components.port102 if port is None:103 return {"https": 443, "http": 80}[self.scheme]

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 105–106why, one step back
105
106 @property

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

lines 107–114why, one step back
107 def path(self) -> str:
108 return self.components.path or "/"109110 @property111 def query(self) -> str:112 return self.components.query or ""113114 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

lines 116–118why, one step back
116 path = self.path
117 if self.query:118 path += "?" + self.query

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 119–121why, one step back
119 return path
120121 @property

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

lines 122–125why, one step back
122 def fragment(self) -> str:
123 return self.components.fragment or ""124125 @property

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 127–129why, one step back
127 return self.components.scheme == "https"
128129 @property

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 130–139why, one step back
130 def is_absolute_url(self) -> bool:
131 """132 Return `True` for absolute URLs such as 'http://example.com/path',133 and `False` for relative URLs such as '/path'.134 """135 # We don't use rfc3986's `is_absolute` because it treats136 # URLs with a fragment portion as not absolute.137 # What we actually care about is if the URL provides138 # a scheme and hostname to which connections should be made.139 return self.components.scheme and self.components.host

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 140–141why, one step back
140
141 @property

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 142–145why, one step back
142 def is_relative_url(self) -> bool:
143 return not self.is_absolute_url144145 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 146–148why, one step back
146 def origin(self) -> "Origin":
147 return Origin(self)148

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 149–152why, one step back
149 def copy_with(self, **kwargs: typing.Any) -> "URL":
150 return URL(self.components.copy_with(**kwargs))151152 def resolve_with(self, base_url: URLTypes) -> "URL":

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 153–156why, one step back
153 """
154 Return an absolute URL, using base_url as the base.155 """156 # We drop any fragment portion, because RFC 3986 strictly

Fix docstringsTom Christiebefore adoption8a227c1

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 160why, one step back
160

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 161–167why, one step back
161 def __hash__(self) -> int:
162 return hash(str(self))163164 def __eq__(self, other: typing.Any) -> bool:165 return isinstance(other, URL) and str(self) == str(other)166167 def __str__(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 169–176why, one step back
169
170 def __repr__(self) -> str:171 class_name = self.__class__.__name__172 url_str = str(self)173 return f"{class_name}({url_str!r})"174175176class Origin:

Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425

lines 177–180why, one step back
177 """
178 The URL scheme and authority information, as a comparable, hashable object.179 """180

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 186–191why, one step back
186 self.port = url.port
187188 def __eq__(self, other: typing.Any) -> bool:189 return (190 isinstance(other, self.__class__)191 and self.is_ssl == other.is_ssl

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 193–196why, one step back
193 and self.port == other.port
194 )195196 def __hash__(self) -> int:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 198–199why, one step back
198
199

Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425

line 200why, one step back
200class QueryParams(typing.Mapping):

Improve class __repr__Tom Christiebefore adoption666d5a8

lines 201–204why, one step back
201 """
202 URL query parameters, as a multi-dict.203 """204

Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425

lines 205–268why, one step back
205 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:
206 assert len(args) < 2, "Too many arguments."207 assert not (args and kwargs), "Cannot mix named and unnamed arguments."208209 value = args[0] if args else kwargs210211 if isinstance(value, str):212 items = parse_qsl(value)213 elif isinstance(value, QueryParams):214 items = value.multi_items()215 elif isinstance(value, list):216 items = value217 else:218 items = value.items() # type: ignore219220 self._list = [(str(k), str(v)) for k, v in items]221 self._dict = {str(k): str(v) for k, v in items}222223 def getlist(self, key: typing.Any) -> typing.List[str]:224 return [item_value for item_key, item_value in self._list if item_key == key]225226 def keys(self) -> typing.KeysView:227 return self._dict.keys()228229 def values(self) -> typing.ValuesView:230 return self._dict.values()231232 def items(self) -> typing.ItemsView:233 return self._dict.items()234235 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:236 return list(self._list)237238 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:239 if key in self._dict:240 return self._dict[key]241 return default242243 def __getitem__(self, key: typing.Any) -> str:244 return self._dict[key]245246 def __contains__(self, key: typing.Any) -> bool:247 return key in self._dict248249 def __iter__(self) -> typing.Iterator[typing.Any]:250 return iter(self.keys())251252 def __len__(self) -> int:253 return len(self._dict)254255 def __eq__(self, other: typing.Any) -> bool:256 if not isinstance(other, self.__class__):257 return False258 return sorted(self._list) == sorted(other._list)259260 def __str__(self) -> str:261 return urlencode(self._list)262263 def __repr__(self) -> str:264 class_name = self.__class__.__name__265 query_string = str(self)266 return f"{class_name}({query_string!r})"267268

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 269–270why, one step back
269class Headers(typing.MutableMapping[str, str]):
270 """

Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425

line 271why, one step back
271 HTTP headers, as a case-insensitive multi-dict.

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 272–273why, one step back
272 """
273

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 275–280why, one step back
275 if headers is None:
276 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]277 elif isinstance(headers, Headers):278 self._list = list(headers.raw)279 elif isinstance(headers, dict):280 self._list = [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 282–285why, one step back
282 for k, v in headers.items()
283 ]284 else:285 self._list = [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 288why, one step back
288 ]

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 290–291why, one step back
290
291 @property

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 292–293why, one step back
292 def encoding(self) -> str:
293 """

Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425

lines 294–295why, one step back
294 Header encoding is mandated as ascii, but we allow fallbacks to utf-8
295 or iso-8859-1.

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 296–320why, one step back
296 """
297 if self._encoding is None:298 for encoding in ["ascii", "utf-8"]:299 for key, value in self.raw:300 try:301 key.decode(encoding)302 value.decode(encoding)303 except UnicodeDecodeError:304 break305 else:306 # The else block runs if 'break' did not occur, meaning307 # all values fitted the encoding.308 self._encoding = encoding309 break310 else:311 # The ISO-8859-1 encoding covers all 256 code points in a byte,312 # so will never raise decode errors.313 self._encoding = "iso-8859-1"314 return self._encoding315316 @encoding.setter317 def encoding(self, value: str) -> None:318 self._encoding = value319320 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 322–325why, one step back
322 """
323 Returns a list of the raw header items, as byte pairs.324 May be mutated in-place.325 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 333–335why, one step back
333
334 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore335 return [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 337–345why, one step back
337 for key, value in self._list
338 ]339340 def get(self, key: str, default: typing.Any = None) -> typing.Any:341 try:342 return self[key]343 except KeyError:344 return default345

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 347–353why, one step back
347 """
348 Return multiple header values.349 """350 get_header_key = key.lower().encode(self.encoding)351352 values = [353 item_value.decode(self.encoding)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 354–357why, one step back
354 for item_key, item_value in self._list
355 if item_key == get_header_key356 ]357

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 358–365why, one step back
358 if not split_commas:
359 return values360361 split_values = []362 for value in values:363 split_values.extend([item.strip() for item in value.split(",")])364 return split_values365

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 367–375why, one step back
367 """
368 Return a single header value.369370 If there are multiple headers with the same key, then we concatenate371 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2372 """373 normalized_key = key.lower().encode(self.encoding)374375 items = []

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 377–382why, one step back
377 if header_key == normalized_key:
378 items.append(header_value.decode(self.encoding))379380 if items:381 return ", ".join(items)382

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 383–389why, one step back
383 raise KeyError(key)
384385 def __setitem__(self, key: str, value: str) -> None:386 """387 Set the header `key` to `value`, removing any duplicate entries.388 Retains insertion order.389 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 392–410why, one step back
392
393 found_indexes = []394 for idx, (item_key, item_value) in enumerate(self._list):395 if item_key == set_key:396 found_indexes.append(idx)397398 for idx in reversed(found_indexes[1:]):399 del self._list[idx]400401 if found_indexes:402 idx = found_indexes[0]403 self._list[idx] = (set_key, set_value)404 else:405 self._list.append((set_key, set_value))406407 def __delitem__(self, key: str) -> None:408 """409 Remove the header `key`.410 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 412–421why, one step back
412
413 pop_indexes = []414 for idx, (item_key, item_value) in enumerate(self._list):415 if item_key == del_key:416 pop_indexes.append(idx)417418 for idx in reversed(pop_indexes):419 del self._list[idx]420421 def __contains__(self, key: typing.Any) -> bool:

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 423–440why, one step back
423 for header_key, header_value in self._list:
424 if header_key == get_header_key:425 return True426 return False427428 def __iter__(self) -> typing.Iterator[typing.Any]:429 return iter(self.keys())430431 def __len__(self) -> int:432 return len(self._list)433434 def __eq__(self, other: typing.Any) -> bool:435 if not isinstance(other, Headers):436 return False437 return sorted(self._list) == sorted(other._list)438439 def __repr__(self) -> str:440 class_name = self.__class__.__name__

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 441–445why, one step back
441
442 encoding_str = ""443 if self.encoding != "ascii":444 encoding_str = f", encoding={self.encoding!r}"445

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 451–458why, one step back
451
452453class Request:454 def __init__(455 self,456 method: str,457 url: typing.Union[str, URL],458 *,

Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425

line 459why, one step back
459 query_params: QueryParamTypes = None,

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 460why, one step back
460 headers: HeaderTypes = None,

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 462–463why, one step back
462 ):
463 self.method = method.upper()

Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425

line 464why, one step back
464 self.url = URL(url, query_params=query_params)

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 468–469why, one step back
468 else:
469 self.is_streaming = True

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 471–476why, one step back
471 self.headers = Headers(headers)
472473 async def read(self) -> bytes:474 """475 Read and return the response content.476 """

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 480–482why, one step back
480 content += part
481 self.content = content482 return self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 487why, one step back
487 yield part

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 488–489why, one step back
488 elif self.content:
489 yield self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 492–498why, one step back
492 """
493 Adds in any default headers. When using the `Client`, this will494 end up being called into by the `prepare_request()` stage.495496 You can omit this behavior by calling `Client.send()` with an497 explicitly built `Request` instance.498 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 499–506why, one step back
499 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]
500501 has_host = "host" in self.headers502 has_content_length = (503 "content-length" in self.headers or "transfer-encoding" in self.headers504 )505 has_accept_encoding = "accept-encoding" in self.headers506

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 514–520why, one step back
514 auto_headers.append((b"content-length", content_length))
515 if not has_accept_encoding:516 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))517518 for item in reversed(auto_headers):519 self.headers.raw.insert(0, item)520

Still truckin' onTom Christiebefore adoption6cb5c0d

lines 521–523why, one step back
521 def __repr__(self) -> str:
522 class_name = self.__class__.__name__523 url = str(self.url)

Improve class __repr__Tom Christiebefore adoption666d5a8

line 524why, one step back
524 return f"<{class_name}({self.method!r}, {url!r})>"

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 525why, one step back
525

Still truckin' onTom Christiebefore adoption6cb5c0d

line 526why, one step back
526

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 527–531why, one step back
527class Response:
528 def __init__(529 self,530 status_code: int,531 *,

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 532–534why, one step back
532 reason_phrase: str = None,
533 protocol: str = None,534 headers: HeaderTypes = None,

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 536–539why, one step back
536 on_close: typing.Callable = None,
537 request: Request = None,538 history: typing.List["Response"] = None,539 ):

Truckin' onTom Christiebefore adoption6b60d95

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

Still truckin' onTom Christiebefore adoption6cb5c0d

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

Truckin' onTom Christiebefore adoption6b60d95

lines 543–544why, one step back
543 except ValueError:
544 self.status_code = status_code

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 546–548why, one step back
546 self.protocol = protocol
547 self.headers = Headers(headers)548

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 551–552why, one step back
551 self.is_stream_consumed = True
552 self._raw_content = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 553why, one step back
553 else:

Response.contentTom Christiebefore adoption4c55113

lines 554–556why, one step back
554 self.is_closed = False
555 self.is_stream_consumed = False556 self._raw_stream = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 557why, one step back
557

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

response.next()Tom Christiebefore adoptiond652479

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 562–564why, one step back
562
563 @property564 def url(self) -> typing.Optional[URL]:

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 565–569why, one step back
565 """
566 Returns the URL for which the request was made.567568 Requires that `request` was provided when instantiating the response.569 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 571–572why, one step back
571
572 @property

Response.contentTom Christiebefore adoption4c55113

lines 573–575why, one step back
573 def content(self) -> bytes:
574 if not hasattr(self, "_content"):575 if hasattr(self, "_raw_content"):

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 576–578why, one step back
576 content = self.decoder.decode(self._raw_content)
577 content += self.decoder.flush()578 self._content = content

Response.contentTom Christiebefore adoption4c55113

lines 579–581why, one step back
579 else:
580 raise ResponseNotRead()581 return self._content

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 582–617why, one step back
582
583 @property584 def text(self) -> str:585 if not hasattr(self, "_text"):586 content = self.content587 if not content:588 self._text = ""589 else:590 encoding = self.encoding591 self._text = content.decode(encoding, errors="replace")592 return self._text593594 @property595 def encoding(self) -> str:596 if not hasattr(self, "_encoding"):597 encoding = self.charset_encoding598 if encoding is None or not is_known_encoding(encoding):599 encoding = self.apparent_encoding600 if encoding is None or not is_known_encoding(encoding):601 encoding = "utf-8"602 self._encoding = encoding603 return self._encoding604605 @encoding.setter606 def encoding(self, value: str) -> None:607 self._encoding = value608609 @property610 def charset_encoding(self) -> typing.Optional[str]:611 """612 Return the encoding, as specified by the Content-Type header.613 """614 content_type = self.headers.get("Content-Type")615 if content_type is None:616 return None617

Truckin' onTom Christiebefore adoption0ca1c84

lines 618–622why, one step back
618 parsed = cgi.parse_header(content_type)
619 media_type, params = parsed[0], parsed[-1]620 if "charset" in params:621 return params["charset"].strip("'\"")622

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

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

Truckin' onTom Christiebefore adoption0ca1c84

lines 626–629why, one step back
626 if media_type.startswith("text/"):
627 return "iso-8859-1"628629 return None

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 630–636why, one step back
630
631 @property632 def apparent_encoding(self) -> typing.Optional[str]:633 """634 Return the encoding, as it appears to autodetection.635 """636 return chardet.detect(self.content)["encoding"]

Response.contentTom Christiebefore adoption4c55113

lines 637–638why, one step back
637
638 @property

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 639–645why, one step back
639 def decoder(self) -> Decoder:
640 """641 Returns a decoder instance which can be used to decode the raw byte642 content, depending on the Content-Encoding used in the response.643 """644 if not hasattr(self, "_decoder"):645 decoders = [] # type: typing.List[Decoder]

Response.contentTom Christiebefore adoption4c55113

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 647–649why, one step back
647 for value in values:
648 value = value.strip().lower()649 decoder_cls = SUPPORTED_DECODERS[value]

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 650–659why, one step back
650 decoders.append(decoder_cls())
651652 if len(decoders) == 1:653 self._decoder = decoders[0]654 elif len(decoders) > 1:655 self._decoder = MultiDecoder(decoders)656 else:657 self._decoder = IdentityDecoder()658659 return self._decoder

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 660–664why, one step back
660
661 async def read(self) -> bytes:662 """663 Read and return the response content.664 """

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 668–670why, one step back
668 content += part
669 self._content = content670 return self._content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 671–676why, one step back
671
672 async def stream(self) -> typing.AsyncIterator[bytes]:673 """674 A byte-iterator over the decoded response content.675 This allows us to handle gzip, deflate, and brotli encoded responses.676 """

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 679–687why, one step back
679 else:
680 async for chunk in self.raw():681 yield self.decoder.decode(chunk)682 yield self.decoder.flush()683684 async def raw(self) -> typing.AsyncIterator[bytes]:685 """686 A byte-iterator over the raw response content.687 """

Response.contentTom Christiebefore adoption4c55113

lines 688–699why, one step back
688 if hasattr(self, "_raw_content"):
689 yield self._raw_content690 else:691 if self.is_stream_consumed:692 raise StreamConsumed()693 if self.is_closed:694 raise ResponseClosed()695696 self.is_stream_consumed = True697 async for part in self._raw_stream:698 yield part699 await self.close()

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 700–713why, one step back
700
701 async def close(self) -> None:702 """703 Close the response and release the connection.704 Automatically called if the response body is read to completion.705 """706 if not self.is_closed:707 self.is_closed = True708 if self.on_close is not None:709 await self.on_close()710711 @property712 def is_redirect(self) -> bool:713 return (

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 714–722why, one step back
714 self.status_code
715 in (716 codes.moved_permanently,717 codes.found,718 codes.see_other,719 codes.temporary_redirect,720 codes.permanent_redirect,721 )722 and "location" in self.headers

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 723why, one step back
723 )

Still truckin' onTom Christiebefore adoption6cb5c0d

lines 724–726why, one step back
724
725 def __repr__(self) -> str:726 class_name = self.__class__.__name__

Improve class __repr__Tom Christiebefore adoption666d5a8

line 727why, one step back
727 return f"<{class_name}({self.status_code}, {self.reason_phrase!r})>"

Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30

lines 728–746why, one step back
728
729 def raise_for_status(self) -> None:730 """731 Raise the `HttpError` if one occurred.732 """733 message = (734 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"735 "For more information check: https://httpstatuses.com/{0.status_code}"736 )737738 if 400 <= self.status_code < 500:739 message = message.format(self, error_type="Client Error")740 elif 500 <= self.status_code < 600:741 message = message.format(self, error_type="Server Error")742 else:743 message = ""744745 if message:746 raise HttpError(message)