Skip to content
Myr

models.py

This file

Path

httpcore/models.py

742 lines · 23.0 KiB · Python

Last changed by

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

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

lines 200–264why, one step back
200class QueryParams(typing.Mapping):
201 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:202 assert len(args) < 2, "Too many arguments."203 assert not (args and kwargs), "Cannot mix named and unnamed arguments."204205 value = args[0] if args else kwargs206207 if isinstance(value, str):208 items = parse_qsl(value)209 elif isinstance(value, QueryParams):210 items = value.multi_items()211 elif isinstance(value, list):212 items = value213 else:214 items = value.items() # type: ignore215216 self._list = [(str(k), str(v)) for k, v in items]217 self._dict = {str(k): str(v) for k, v in items}218219 def getlist(self, key: typing.Any) -> typing.List[str]:220 return [item_value for item_key, item_value in self._list if item_key == key]221222 def keys(self) -> typing.KeysView:223 return self._dict.keys()224225 def values(self) -> typing.ValuesView:226 return self._dict.values()227228 def items(self) -> typing.ItemsView:229 return self._dict.items()230231 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:232 return list(self._list)233234 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:235 if key in self._dict:236 return self._dict[key]237 return default238239 def __getitem__(self, key: typing.Any) -> str:240 return self._dict[key]241242 def __contains__(self, key: typing.Any) -> bool:243 return key in self._dict244245 def __iter__(self) -> typing.Iterator[typing.Any]:246 return iter(self.keys())247248 def __len__(self) -> int:249 return len(self._dict)250251 def __eq__(self, other: typing.Any) -> bool:252 if not isinstance(other, self.__class__):253 return False254 return sorted(self._list) == sorted(other._list)255256 def __str__(self) -> str:257 return urlencode(self._list)258259 def __repr__(self) -> str:260 class_name = self.__class__.__name__261 query_string = str(self)262 return f"{class_name}({query_string!r})"263264

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 268–269why, one step back
268 """
269

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 278–281why, one step back
278 for k, v in headers.items()
279 ]280 else:281 self._list = [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 284why, one step back
284 ]

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 286–287why, one step back
286
287 @property

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

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

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 292–316why, one step back
292 """
293 if self._encoding is None:294 for encoding in ["ascii", "utf-8"]:295 for key, value in self.raw:296 try:297 key.decode(encoding)298 value.decode(encoding)299 except UnicodeDecodeError:300 break301 else:302 # The else block runs if 'break' did not occur, meaning303 # all values fitted the encoding.304 self._encoding = encoding305 break306 else:307 # The ISO-8859-1 encoding covers all 256 code points in a byte,308 # so will never raise decode errors.309 self._encoding = "iso-8859-1"310 return self._encoding311312 @encoding.setter313 def encoding(self, value: str) -> None:314 self._encoding = value315316 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 318–321why, one step back
318 """
319 Returns a list of the raw header items, as byte pairs.320 May be mutated in-place.321 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 329–331why, one step back
329
330 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore331 return [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 333–341why, one step back
333 for key, value in self._list
334 ]335336 def get(self, key: str, default: typing.Any = None) -> typing.Any:337 try:338 return self[key]339 except KeyError:340 return default341

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 343–349why, one step back
343 """
344 Return multiple header values.345 """346 get_header_key = key.lower().encode(self.encoding)347348 values = [349 item_value.decode(self.encoding)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 350–353why, one step back
350 for item_key, item_value in self._list
351 if item_key == get_header_key352 ]353

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 354–361why, one step back
354 if not split_commas:
355 return values356357 split_values = []358 for value in values:359 split_values.extend([item.strip() for item in value.split(",")])360 return split_values361

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 363–371why, one step back
363 """
364 Return a single header value.365366 If there are multiple headers with the same key, then we concatenate367 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2368 """369 normalized_key = key.lower().encode(self.encoding)370371 items = []

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 379–385why, one step back
379 raise KeyError(key)
380381 def __setitem__(self, key: str, value: str) -> None:382 """383 Set the header `key` to `value`, removing any duplicate entries.384 Retains insertion order.385 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 388–406why, one step back
388
389 found_indexes = []390 for idx, (item_key, item_value) in enumerate(self._list):391 if item_key == set_key:392 found_indexes.append(idx)393394 for idx in reversed(found_indexes[1:]):395 del self._list[idx]396397 if found_indexes:398 idx = found_indexes[0]399 self._list[idx] = (set_key, set_value)400 else:401 self._list.append((set_key, set_value))402403 def __delitem__(self, key: str) -> None:404 """405 Remove the header `key`.406 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 408–417why, one step back
408
409 pop_indexes = []410 for idx, (item_key, item_value) in enumerate(self._list):411 if item_key == del_key:412 pop_indexes.append(idx)413414 for idx in reversed(pop_indexes):415 del self._list[idx]416417 def __contains__(self, key: typing.Any) -> bool:

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 419–436why, one step back
419 for header_key, header_value in self._list:
420 if header_key == get_header_key:421 return True422 return False423424 def __iter__(self) -> typing.Iterator[typing.Any]:425 return iter(self.keys())426427 def __len__(self) -> int:428 return len(self._list)429430 def __eq__(self, other: typing.Any) -> bool:431 if not isinstance(other, Headers):432 return False433 return sorted(self._list) == sorted(other._list)434435 def __repr__(self) -> str:436 class_name = self.__class__.__name__

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 437–441why, one step back
437
438 encoding_str = ""439 if self.encoding != "ascii":440 encoding_str = f", encoding={self.encoding!r}"441

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 447–454why, one step back
447
448449class Request:450 def __init__(451 self,452 method: str,453 url: typing.Union[str, URL],454 *,

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 458–459why, one step back
458 ):
459 self.method = method.upper()

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

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 464–465why, one step back
464 else:
465 self.is_streaming = True

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 467–472why, one step back
467 self.headers = Headers(headers)
468469 async def read(self) -> bytes:470 """471 Read and return the response content.472 """

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 476–478why, one step back
476 content += part
477 self.content = content478 return self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 483why, one step back
483 yield part

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 484–485why, one step back
484 elif self.content:
485 yield self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 488–494why, one step back
488 """
489 Adds in any default headers. When using the `Client`, this will490 end up being called into by the `prepare_request()` stage.491492 You can omit this behavior by calling `Client.send()` with an493 explicitly built `Request` instance.494 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 495–502why, one step back
495 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]
496497 has_host = "host" in self.headers498 has_content_length = (499 "content-length" in self.headers or "transfer-encoding" in self.headers500 )501 has_accept_encoding = "accept-encoding" in self.headers502

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Still truckin' onTom Christiebefore adoption6cb5c0d

lines 517–520why, one step back
517 def __repr__(self) -> str:
518 class_name = self.__class__.__name__519 url = str(self.url)520 return f"<{class_name}({self.method}, {url})>"

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 521why, one step back
521

Still truckin' onTom Christiebefore adoption6cb5c0d

line 522why, one step back
522

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 523–527why, one step back
523class Response:
524 def __init__(525 self,526 status_code: int,527 *,

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 528–530why, one step back
528 reason_phrase: str = None,
529 protocol: str = None,530 headers: HeaderTypes = None,

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 532–535why, one step back
532 on_close: typing.Callable = None,
533 request: Request = None,534 history: typing.List["Response"] = None,535 ):

Truckin' onTom Christiebefore adoption6b60d95

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

Still truckin' onTom Christiebefore adoption6cb5c0d

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

Truckin' onTom Christiebefore adoption6b60d95

lines 539–540why, one step back
539 except ValueError:
540 self.status_code = status_code

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 542–544why, one step back
542 self.protocol = protocol
543 self.headers = Headers(headers)544

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 547–548why, one step back
547 self.is_stream_consumed = True
548 self._raw_content = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 549why, one step back
549 else:

Response.contentTom Christiebefore adoption4c55113

lines 550–552why, one step back
550 self.is_closed = False
551 self.is_stream_consumed = False552 self._raw_stream = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 553why, one step back
553

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

response.next()Tom Christiebefore adoptiond652479

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 558–560why, one step back
558
559 @property560 def url(self) -> typing.Optional[URL]:

Clean up response interfaceTom Christiebefore adoption4d908d0

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 567–568why, one step back
567
568 @property

Response.contentTom Christiebefore adoption4c55113

lines 569–571why, one step back
569 def content(self) -> bytes:
570 if not hasattr(self, "_content"):571 if hasattr(self, "_raw_content"):

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 572–574why, one step back
572 content = self.decoder.decode(self._raw_content)
573 content += self.decoder.flush()574 self._content = content

Response.contentTom Christiebefore adoption4c55113

lines 575–577why, one step back
575 else:
576 raise ResponseNotRead()577 return self._content

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 578–613why, one step back
578
579 @property580 def text(self) -> str:581 if not hasattr(self, "_text"):582 content = self.content583 if not content:584 self._text = ""585 else:586 encoding = self.encoding587 self._text = content.decode(encoding, errors="replace")588 return self._text589590 @property591 def encoding(self) -> str:592 if not hasattr(self, "_encoding"):593 encoding = self.charset_encoding594 if encoding is None or not is_known_encoding(encoding):595 encoding = self.apparent_encoding596 if encoding is None or not is_known_encoding(encoding):597 encoding = "utf-8"598 self._encoding = encoding599 return self._encoding600601 @encoding.setter602 def encoding(self, value: str) -> None:603 self._encoding = value604605 @property606 def charset_encoding(self) -> typing.Optional[str]:607 """608 Return the encoding, as specified by the Content-Type header.609 """610 content_type = self.headers.get("Content-Type")611 if content_type is None:612 return None613

Truckin' onTom Christiebefore adoption0ca1c84

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

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

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

Truckin' onTom Christiebefore adoption0ca1c84

lines 622–625why, one step back
622 if media_type.startswith("text/"):
623 return "iso-8859-1"624625 return None

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 626–632why, one step back
626
627 @property628 def apparent_encoding(self) -> typing.Optional[str]:629 """630 Return the encoding, as it appears to autodetection.631 """632 return chardet.detect(self.content)["encoding"]

Response.contentTom Christiebefore adoption4c55113

lines 633–634why, one step back
633
634 @property

Clean up response interfaceTom Christiebefore adoption4d908d0

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

Response.contentTom Christiebefore adoption4c55113

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 643–645why, one step back
643 for value in values:
644 value = value.strip().lower()645 decoder_cls = SUPPORTED_DECODERS[value]

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 646–655why, one step back
646 decoders.append(decoder_cls())
647648 if len(decoders) == 1:649 self._decoder = decoders[0]650 elif len(decoders) > 1:651 self._decoder = MultiDecoder(decoders)652 else:653 self._decoder = IdentityDecoder()654655 return self._decoder

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 656–660why, one step back
656
657 async def read(self) -> bytes:658 """659 Read and return the response content.660 """

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 664–666why, one step back
664 content += part
665 self._content = content666 return self._content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 675–683why, one step back
675 else:
676 async for chunk in self.raw():677 yield self.decoder.decode(chunk)678 yield self.decoder.flush()679680 async def raw(self) -> typing.AsyncIterator[bytes]:681 """682 A byte-iterator over the raw response content.683 """

Response.contentTom Christiebefore adoption4c55113

lines 684–695why, one step back
684 if hasattr(self, "_raw_content"):
685 yield self._raw_content686 else:687 if self.is_stream_consumed:688 raise StreamConsumed()689 if self.is_closed:690 raise ResponseClosed()691692 self.is_stream_consumed = True693 async for part in self._raw_stream:694 yield part695 await self.close()

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 696–709why, one step back
696
697 async def close(self) -> None:698 """699 Close the response and release the connection.700 Automatically called if the response body is read to completion.701 """702 if not self.is_closed:703 self.is_closed = True704 if self.on_close is not None:705 await self.on_close()706707 @property708 def is_redirect(self) -> bool:709 return (

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 710–718why, one step back
710 self.status_code
711 in (712 codes.moved_permanently,713 codes.found,714 codes.see_other,715 codes.temporary_redirect,716 codes.permanent_redirect,717 )718 and "location" in self.headers

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 719why, one step back
719 )

Still truckin' onTom Christiebefore adoption6cb5c0d

lines 720–723why, one step back
720
721 def __repr__(self) -> str:722 class_name = self.__class__.__name__723 return f"<{class_name}(status_code={self.status_code})>"

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

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