Skip to content
Myr

models.py

This file

Path

httpcore/models.py

753 lines · 23.4 KiB · Python

Last changed by

Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53

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

Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53

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

Finessing interfaceTom Christiebefore adoptiond7619a9

line 48why, one step back
48

Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53

line 49why, one step back
49ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]

Finessing interfaceTom Christiebefore adoptiond7619a9

line 50why, one step back
50

Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53

line 51why, one step back
51

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 52why, one step back
52class URL:

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

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 63–65why, one step back
63 else:
64 self.components = url.components65

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Fix docstringsTom Christiebefore adoption8a227c1

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 73–74why, one step back
73 self.components = self.components.normalize()
74

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

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 88–90why, one step back
88
89 @property90 def scheme(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 92–93why, one step back
92
93 @property

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 96–97why, one step back
96
97 @property

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 107–108why, one step back
107
108 @property

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

lines 109–116why, one step back
109 def path(self) -> str:
110 return self.components.path or "/"111112 @property113 def query(self) -> str:114 return self.components.query or ""115116 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 121–123why, one step back
121 return path
122123 @property

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

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 142–143why, one step back
142
143 @property

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 144–147why, one step back
144 def is_relative_url(self) -> bool:
145 return not self.is_absolute_url146147 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Fix docstringsTom Christiebefore adoption8a227c1

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 162why, one step back
162

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 163–169why, one step back
163 def __hash__(self) -> int:
164 return hash(str(self))165166 def __eq__(self, other: typing.Any) -> bool:167 return isinstance(other, URL) and str(self) == str(other)168169 def __str__(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 171–178why, one step back
171
172 def __repr__(self) -> str:173 class_name = self.__class__.__name__174 url_str = str(self)175 return f"{class_name}({url_str!r})"176177178class Origin:

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

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 188–193why, one step back
188 self.port = url.port
189190 def __eq__(self, other: typing.Any) -> bool:191 return (192 isinstance(other, self.__class__)193 and self.is_ssl == other.is_ssl

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 195–198why, one step back
195 and self.port == other.port
196 )197198 def __hash__(self) -> int:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 200–201why, one step back
200
201

Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53

line 202why, one step back
202class QueryParams(typing.Mapping[str, str]):

Improve class __repr__Tom Christiebefore adoption666d5a8

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

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

lines 207–270why, one step back
207 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:
208 assert len(args) < 2, "Too many arguments."209 assert not (args and kwargs), "Cannot mix named and unnamed arguments."210211 value = args[0] if args else kwargs212213 if isinstance(value, str):214 items = parse_qsl(value)215 elif isinstance(value, QueryParams):216 items = value.multi_items()217 elif isinstance(value, list):218 items = value219 else:220 items = value.items() # type: ignore221222 self._list = [(str(k), str(v)) for k, v in items]223 self._dict = {str(k): str(v) for k, v in items}224225 def getlist(self, key: typing.Any) -> typing.List[str]:226 return [item_value for item_key, item_value in self._list if item_key == key]227228 def keys(self) -> typing.KeysView:229 return self._dict.keys()230231 def values(self) -> typing.ValuesView:232 return self._dict.values()233234 def items(self) -> typing.ItemsView:235 return self._dict.items()236237 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:238 return list(self._list)239240 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:241 if key in self._dict:242 return self._dict[key]243 return default244245 def __getitem__(self, key: typing.Any) -> str:246 return self._dict[key]247248 def __contains__(self, key: typing.Any) -> bool:249 return key in self._dict250251 def __iter__(self) -> typing.Iterator[typing.Any]:252 return iter(self.keys())253254 def __len__(self) -> int:255 return len(self._dict)256257 def __eq__(self, other: typing.Any) -> bool:258 if not isinstance(other, self.__class__):259 return False260 return sorted(self._list) == sorted(other._list)261262 def __str__(self) -> str:263 return urlencode(self._list)264265 def __repr__(self) -> str:266 class_name = self.__class__.__name__267 query_string = str(self)268 return f"{class_name}({query_string!r})"269270

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 274–275why, one step back
274 """
275

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 290why, one step back
290 ]

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 292–293why, one step back
292
293 @property

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

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

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 298–322why, one step back
298 """
299 if self._encoding is None:300 for encoding in ["ascii", "utf-8"]:301 for key, value in self.raw:302 try:303 key.decode(encoding)304 value.decode(encoding)305 except UnicodeDecodeError:306 break307 else:308 # The else block runs if 'break' did not occur, meaning309 # all values fitted the encoding.310 self._encoding = encoding311 break312 else:313 # The ISO-8859-1 encoding covers all 256 code points in a byte,314 # so will never raise decode errors.315 self._encoding = "iso-8859-1"316 return self._encoding317318 @encoding.setter319 def encoding(self, value: str) -> None:320 self._encoding = value321322 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 339–347why, one step back
339 for key, value in self._list
340 ]341342 def get(self, key: str, default: typing.Any = None) -> typing.Any:343 try:344 return self[key]345 except KeyError:346 return default347

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 349–355why, one step back
349 """
350 Return multiple header values.351 """352 get_header_key = key.lower().encode(self.encoding)353354 values = [355 item_value.decode(self.encoding)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 356–359why, one step back
356 for item_key, item_value in self._list
357 if item_key == get_header_key358 ]359

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 360–367why, one step back
360 if not split_commas:
361 return values362363 split_values = []364 for value in values:365 split_values.extend([item.strip() for item in value.split(",")])366 return split_values367

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 369–377why, one step back
369 """
370 Return a single header value.371372 If there are multiple headers with the same key, then we concatenate373 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2374 """375 normalized_key = key.lower().encode(self.encoding)376377 items = []

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 379–384why, one step back
379 if header_key == normalized_key:
380 items.append(header_value.decode(self.encoding))381382 if items:383 return ", ".join(items)384

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 394–412why, one step back
394
395 found_indexes = []396 for idx, (item_key, item_value) in enumerate(self._list):397 if item_key == set_key:398 found_indexes.append(idx)399400 for idx in reversed(found_indexes[1:]):401 del self._list[idx]402403 if found_indexes:404 idx = found_indexes[0]405 self._list[idx] = (set_key, set_value)406 else:407 self._list.append((set_key, set_value))408409 def __delitem__(self, key: str) -> None:410 """411 Remove the header `key`.412 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 425–442why, one step back
425 for header_key, header_value in self._list:
426 if header_key == get_header_key:427 return True428 return False429430 def __iter__(self) -> typing.Iterator[typing.Any]:431 return iter(self.keys())432433 def __len__(self) -> int:434 return len(self._list)435436 def __eq__(self, other: typing.Any) -> bool:437 if not isinstance(other, Headers):438 return False439 return sorted(self._list) == sorted(other._list)440441 def __repr__(self) -> str:442 class_name = self.__class__.__name__

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 453–460why, one step back
453
454455class Request:456 def __init__(457 self,458 method: str,459 url: typing.Union[str, URL],460 *,

Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53

line 461why, one step back
461 data: RequestData = b"",

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 463–465why, one step back
463 headers: HeaderTypes = None,
464 ):465 self.method = method.upper()

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

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

Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53

lines 467–469why, one step back
467 self.headers = Headers(headers)
468469 if isinstance(data, bytes):

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53

lines 471–475why, one step back
471 self.content = data
472 elif isinstance(data, dict):473 self.is_streaming = False474 self.content = urlencode(data, doseq=True).encode("utf-8")475 self.headers["Content-Type"] = "application/x-www-form-urlencoded"

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 476–477why, one step back
476 else:
477 self.is_streaming = True

Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53

line 478why, one step back
478 self.content_aiter = data

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 479–483why, one step back
479
480 async def read(self) -> bytes:481 """482 Read and return the response content.483 """

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 487–489why, one step back
487 content += part
488 self.content = content489 return self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 494why, one step back
494 yield part

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 495–496why, one step back
495 elif self.content:
496 yield self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 499–505why, one step back
499 """
500 Adds in any default headers. When using the `Client`, this will501 end up being called into by the `prepare_request()` stage.502503 You can omit this behavior by calling `Client.send()` with an504 explicitly built `Request` instance.505 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 506–513why, one step back
506 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]
507508 has_host = "host" in self.headers509 has_content_length = (510 "content-length" in self.headers or "transfer-encoding" in self.headers511 )512 has_accept_encoding = "accept-encoding" in self.headers513

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 521–527why, one step back
521 auto_headers.append((b"content-length", content_length))
522 if not has_accept_encoding:523 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))524525 for item in reversed(auto_headers):526 self.headers.raw.insert(0, item)527

Still truckin' onTom Christiebefore adoption6cb5c0d

lines 528–530why, one step back
528 def __repr__(self) -> str:
529 class_name = self.__class__.__name__530 url = str(self.url)

Improve class __repr__Tom Christiebefore adoption666d5a8

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 532why, one step back
532

Still truckin' onTom Christiebefore adoption6cb5c0d

line 533why, one step back
533

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 534–538why, one step back
534class Response:
535 def __init__(536 self,537 status_code: int,538 *,

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 539–541why, one step back
539 reason_phrase: str = None,
540 protocol: str = None,541 headers: HeaderTypes = None,

Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53

line 542why, one step back
542 content: ResponseContent = b"",

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 543–546why, one step back
543 on_close: typing.Callable = None,
544 request: Request = None,545 history: typing.List["Response"] = None,546 ):

Truckin' onTom Christiebefore adoption6b60d95

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

Still truckin' onTom Christiebefore adoption6cb5c0d

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

Truckin' onTom Christiebefore adoption6b60d95

lines 550–551why, one step back
550 except ValueError:
551 self.status_code = status_code

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 553–555why, one step back
553 self.protocol = protocol
554 self.headers = Headers(headers)555

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 558–559why, one step back
558 self.is_stream_consumed = True
559 self._raw_content = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 560why, one step back
560 else:

Response.contentTom Christiebefore adoption4c55113

lines 561–563why, one step back
561 self.is_closed = False
562 self.is_stream_consumed = False563 self._raw_stream = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 564why, one step back
564

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

response.next()Tom Christiebefore adoptiond652479

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 569–571why, one step back
569
570 @property571 def url(self) -> typing.Optional[URL]:

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 572–576why, one step back
572 """
573 Returns the URL for which the request was made.574575 Requires that `request` was provided when instantiating the response.576 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 578–579why, one step back
578
579 @property

Response.contentTom Christiebefore adoption4c55113

lines 580–582why, one step back
580 def content(self) -> bytes:
581 if not hasattr(self, "_content"):582 if hasattr(self, "_raw_content"):

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 583–585why, one step back
583 content = self.decoder.decode(self._raw_content)
584 content += self.decoder.flush()585 self._content = content

Response.contentTom Christiebefore adoption4c55113

lines 586–588why, one step back
586 else:
587 raise ResponseNotRead()588 return self._content

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 589–624why, one step back
589
590 @property591 def text(self) -> str:592 if not hasattr(self, "_text"):593 content = self.content594 if not content:595 self._text = ""596 else:597 encoding = self.encoding598 self._text = content.decode(encoding, errors="replace")599 return self._text600601 @property602 def encoding(self) -> str:603 if not hasattr(self, "_encoding"):604 encoding = self.charset_encoding605 if encoding is None or not is_known_encoding(encoding):606 encoding = self.apparent_encoding607 if encoding is None or not is_known_encoding(encoding):608 encoding = "utf-8"609 self._encoding = encoding610 return self._encoding611612 @encoding.setter613 def encoding(self, value: str) -> None:614 self._encoding = value615616 @property617 def charset_encoding(self) -> typing.Optional[str]:618 """619 Return the encoding, as specified by the Content-Type header.620 """621 content_type = self.headers.get("Content-Type")622 if content_type is None:623 return None624

Truckin' onTom Christiebefore adoption0ca1c84

lines 625–629why, one step back
625 parsed = cgi.parse_header(content_type)
626 media_type, params = parsed[0], parsed[-1]627 if "charset" in params:628 return params["charset"].strip("'\"")629

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

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

Truckin' onTom Christiebefore adoption0ca1c84

lines 633–636why, one step back
633 if media_type.startswith("text/"):
634 return "iso-8859-1"635636 return None

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 637–643why, one step back
637
638 @property639 def apparent_encoding(self) -> typing.Optional[str]:640 """641 Return the encoding, as it appears to autodetection.642 """643 return chardet.detect(self.content)["encoding"]

Response.contentTom Christiebefore adoption4c55113

lines 644–645why, one step back
644
645 @property

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 646–652why, one step back
646 def decoder(self) -> Decoder:
647 """648 Returns a decoder instance which can be used to decode the raw byte649 content, depending on the Content-Encoding used in the response.650 """651 if not hasattr(self, "_decoder"):652 decoders = [] # type: typing.List[Decoder]

Response.contentTom Christiebefore adoption4c55113

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 654–656why, one step back
654 for value in values:
655 value = value.strip().lower()656 decoder_cls = SUPPORTED_DECODERS[value]

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 657–666why, one step back
657 decoders.append(decoder_cls())
658659 if len(decoders) == 1:660 self._decoder = decoders[0]661 elif len(decoders) > 1:662 self._decoder = MultiDecoder(decoders)663 else:664 self._decoder = IdentityDecoder()665666 return self._decoder

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 667–671why, one step back
667
668 async def read(self) -> bytes:669 """670 Read and return the response content.671 """

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 675–677why, one step back
675 content += part
676 self._content = content677 return self._content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 678–683why, one step back
678
679 async def stream(self) -> typing.AsyncIterator[bytes]:680 """681 A byte-iterator over the decoded response content.682 This allows us to handle gzip, deflate, and brotli encoded responses.683 """

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 686–694why, one step back
686 else:
687 async for chunk in self.raw():688 yield self.decoder.decode(chunk)689 yield self.decoder.flush()690691 async def raw(self) -> typing.AsyncIterator[bytes]:692 """693 A byte-iterator over the raw response content.694 """

Response.contentTom Christiebefore adoption4c55113

lines 695–706why, one step back
695 if hasattr(self, "_raw_content"):
696 yield self._raw_content697 else:698 if self.is_stream_consumed:699 raise StreamConsumed()700 if self.is_closed:701 raise ResponseClosed()702703 self.is_stream_consumed = True704 async for part in self._raw_stream:705 yield part706 await self.close()

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 707–720why, one step back
707
708 async def close(self) -> None:709 """710 Close the response and release the connection.711 Automatically called if the response body is read to completion.712 """713 if not self.is_closed:714 self.is_closed = True715 if self.on_close is not None:716 await self.on_close()717718 @property719 def is_redirect(self) -> bool:720 return (

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 721–729why, one step back
721 self.status_code
722 in (723 codes.moved_permanently,724 codes.found,725 codes.see_other,726 codes.temporary_redirect,727 codes.permanent_redirect,728 )729 and "location" in self.headers

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 730why, one step back
730 )

Still truckin' onTom Christiebefore adoption6cb5c0d

lines 731–733why, one step back
731
732 def __repr__(self) -> str:733 class_name = self.__class__.__name__

Improve class __repr__Tom Christiebefore adoption666d5a8

line 734why, one step back
734 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 735–753why, one step back
735
736 def raise_for_status(self) -> None:737 """738 Raise the `HttpError` if one occurred.739 """740 message = (741 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"742 "For more information check: https://httpstatuses.com/{0.status_code}"743 )744745 if 400 <= self.status_code < 500:746 message = message.format(self, error_type="Client Error")747 elif 500 <= self.status_code < 600:748 message = message.format(self, error_type="Server Error")749 else:750 message = ""751752 if message:753 raise HttpError(message)