Skip to content
Myr

models.py

This file

Path

httpcore/models.py

839 lines · 25.7 KiB · Python

Last changed by

Auth (#65)Tom Christiebefore adoption5afa7dd

History of this file

Take it

Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0

line 1why, one step back
1import asyncio

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

line 2why, one step back
2import cgi

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 3why, one step back
3import typing

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 5why, one step back
5

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

line 6why, one step back
6import chardet

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

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

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

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

Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369

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

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 30why, one step back
30

Finessing interfaceTom Christiebefore adoptiond7619a9

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 32why, one step back
32

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

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

Finessing interfaceTom Christiebefore adoptiond7619a9

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

Auth (#65)Tom Christiebefore adoption5afa7dd

lines 46–50why, one step back
46AuthTypes = typing.Union[
47 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],48 typing.Callable[["Request"], "Request"]49]50

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

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

Finessing interfaceTom Christiebefore adoptiond7619a9

line 52why, one step back
52

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

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

Finessing interfaceTom Christiebefore adoptiond7619a9

line 54why, one step back
54

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

line 55why, one step back
55

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 56why, one step back
56class URL:

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

lines 57–62why, one step back
57 def __init__(
58 self,59 url: URLTypes,60 allow_relative: bool = False,61 query_params: QueryParamTypes = None,62 ) -> None:

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 67–69why, one step back
67 else:
68 self.components = url.components69

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 70–75why, one step back
70 # Handle IDNA domain names.
71 if self.components.authority:72 idna_authority = self.components.authority.encode("idna").decode("ascii")73 if idna_authority != self.components.authority:74 self.components = self.components.copy_with(authority=idna_authority)75

Fix docstringsTom Christiebefore adoption8a227c1

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 77–78why, one step back
77 self.components = self.components.normalize()
78

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

lines 79–83why, one step back
79 # Add any query parameters.
80 if query_params:81 query_string = str(QueryParams(query_params))82 self.components = self.components.copy_with(query=query_string)83

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 92–94why, one step back
92
93 @property94 def scheme(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 95why, one step back
95 return self.components.scheme 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 authority(self) -> str:
99 return self.components.authority or ""

Auth (#65)Tom Christiebefore adoption5afa7dd

lines 100–109why, one step back
100
101 @property102 def username(self) -> str:103 userinfo = self.components.userinfo or ""104 return userinfo.partition(':')[0]105106 @property107 def password(self) -> str:108 userinfo = self.components.userinfo or ""109 return userinfo.partition(':')[2]

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 110–111why, one step back
110
111 @property

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 114–119why, one step back
114
115 @property116 def port(self) -> int:117 port = self.components.port118 if port is None:119 return {"https": 443, "http": 80}[self.scheme]

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

lines 123–130why, one step back
123 def path(self) -> str:
124 return self.components.path or "/"125126 @property127 def query(self) -> str:128 return self.components.query or ""129130 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

lines 132–134why, one step back
132 path = self.path
133 if self.query:134 path += "?" + self.query

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 135–137why, one step back
135 return path
136137 @property

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

lines 138–141why, one step back
138 def fragment(self) -> str:
139 return self.components.fragment or ""140141 @property

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 143–145why, one step back
143 return self.components.scheme == "https"
144145 @property

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 146–155why, one step back
146 def is_absolute_url(self) -> bool:
147 """148 Return `True` for absolute URLs such as 'http://example.com/path',149 and `False` for relative URLs such as '/path'.150 """151 # We don't use rfc3986's `is_absolute` because it treats152 # URLs with a fragment portion as not absolute.153 # What we actually care about is if the URL provides154 # a scheme and hostname to which connections should be made.155 return self.components.scheme and self.components.host

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 156–157why, one step back
156
157 @property

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 158–161why, one step back
158 def is_relative_url(self) -> bool:
159 return not self.is_absolute_url160161 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 162–164why, one step back
162 def origin(self) -> "Origin":
163 return Origin(self)164

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 165–168why, one step back
165 def copy_with(self, **kwargs: typing.Any) -> "URL":
166 return URL(self.components.copy_with(**kwargs))167168 def resolve_with(self, base_url: URLTypes) -> "URL":

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 169–172why, one step back
169 """
170 Return an absolute URL, using base_url as the base.171 """172 # We drop any fragment portion, because RFC 3986 strictly

Fix docstringsTom Christiebefore adoption8a227c1

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 176why, one step back
176

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 177–183why, one step back
177 def __hash__(self) -> int:
178 return hash(str(self))179180 def __eq__(self, other: typing.Any) -> bool:181 return isinstance(other, URL) and str(self) == str(other)182183 def __str__(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 185–192why, one step back
185
186 def __repr__(self) -> str:187 class_name = self.__class__.__name__188 url_str = str(self)189 return f"{class_name}({url_str!r})"190191192class Origin:

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

lines 193–196why, one step back
193 """
194 The URL scheme and authority information, as a comparable, hashable object.195 """196

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 202–207why, one step back
202 self.port = url.port
203204 def __eq__(self, other: typing.Any) -> bool:205 return (206 isinstance(other, self.__class__)207 and self.is_ssl == other.is_ssl

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 209–212why, one step back
209 and self.port == other.port
210 )211212 def __hash__(self) -> int:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 214–215why, one step back
214
215

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

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

Improve class __repr__Tom Christiebefore adoption666d5a8

lines 217–220why, one step back
217 """
218 URL query parameters, as a multi-dict.219 """220

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

lines 221–284why, one step back
221 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:
222 assert len(args) < 2, "Too many arguments."223 assert not (args and kwargs), "Cannot mix named and unnamed arguments."224225 value = args[0] if args else kwargs226227 if isinstance(value, str):228 items = parse_qsl(value)229 elif isinstance(value, QueryParams):230 items = value.multi_items()231 elif isinstance(value, list):232 items = value233 else:234 items = value.items() # type: ignore235236 self._list = [(str(k), str(v)) for k, v in items]237 self._dict = {str(k): str(v) for k, v in items}238239 def getlist(self, key: typing.Any) -> typing.List[str]:240 return [item_value for item_key, item_value in self._list if item_key == key]241242 def keys(self) -> typing.KeysView:243 return self._dict.keys()244245 def values(self) -> typing.ValuesView:246 return self._dict.values()247248 def items(self) -> typing.ItemsView:249 return self._dict.items()250251 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:252 return list(self._list)253254 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:255 if key in self._dict:256 return self._dict[key]257 return default258259 def __getitem__(self, key: typing.Any) -> str:260 return self._dict[key]261262 def __contains__(self, key: typing.Any) -> bool:263 return key in self._dict264265 def __iter__(self) -> typing.Iterator[typing.Any]:266 return iter(self.keys())267268 def __len__(self) -> int:269 return len(self._dict)270271 def __eq__(self, other: typing.Any) -> bool:272 if not isinstance(other, self.__class__):273 return False274 return sorted(self._list) == sorted(other._list)275276 def __str__(self) -> str:277 return urlencode(self._list)278279 def __repr__(self) -> str:280 class_name = self.__class__.__name__281 query_string = str(self)282 return f"{class_name}({query_string!r})"283284

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 288–289why, one step back
288 """
289

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 291–296why, one step back
291 if headers is None:
292 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]293 elif isinstance(headers, Headers):294 self._list = list(headers.raw)295 elif isinstance(headers, dict):296 self._list = [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 298–301why, one step back
298 for k, v in headers.items()
299 ]300 else:301 self._list = [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 304why, one step back
304 ]

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 306–307why, one step back
306
307 @property

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

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

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 312–336why, one step back
312 """
313 if self._encoding is None:314 for encoding in ["ascii", "utf-8"]:315 for key, value in self.raw:316 try:317 key.decode(encoding)318 value.decode(encoding)319 except UnicodeDecodeError:320 break321 else:322 # The else block runs if 'break' did not occur, meaning323 # all values fitted the encoding.324 self._encoding = encoding325 break326 else:327 # The ISO-8859-1 encoding covers all 256 code points in a byte,328 # so will never raise decode errors.329 self._encoding = "iso-8859-1"330 return self._encoding331332 @encoding.setter333 def encoding(self, value: str) -> None:334 self._encoding = value335336 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 338–341why, one step back
338 """
339 Returns a list of the raw header items, as byte pairs.340 May be mutated in-place.341 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 349–351why, one step back
349
350 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore351 return [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 353–361why, one step back
353 for key, value in self._list
354 ]355356 def get(self, key: str, default: typing.Any = None) -> typing.Any:357 try:358 return self[key]359 except KeyError:360 return default361

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 363–369why, one step back
363 """
364 Return multiple header values.365 """366 get_header_key = key.lower().encode(self.encoding)367368 values = [369 item_value.decode(self.encoding)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 370–373why, one step back
370 for item_key, item_value in self._list
371 if item_key == get_header_key372 ]373

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 374–381why, one step back
374 if not split_commas:
375 return values376377 split_values = []378 for value in values:379 split_values.extend([item.strip() for item in value.split(",")])380 return split_values381

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 383–391why, one step back
383 """
384 Return a single header value.385386 If there are multiple headers with the same key, then we concatenate387 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2388 """389 normalized_key = key.lower().encode(self.encoding)390391 items = []

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 393–398why, one step back
393 if header_key == normalized_key:
394 items.append(header_value.decode(self.encoding))395396 if items:397 return ", ".join(items)398

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 399–405why, one step back
399 raise KeyError(key)
400401 def __setitem__(self, key: str, value: str) -> None:402 """403 Set the header `key` to `value`, removing any duplicate entries.404 Retains insertion order.405 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 408–426why, one step back
408
409 found_indexes = []410 for idx, (item_key, item_value) in enumerate(self._list):411 if item_key == set_key:412 found_indexes.append(idx)413414 for idx in reversed(found_indexes[1:]):415 del self._list[idx]416417 if found_indexes:418 idx = found_indexes[0]419 self._list[idx] = (set_key, set_value)420 else:421 self._list.append((set_key, set_value))422423 def __delitem__(self, key: str) -> None:424 """425 Remove the header `key`.426 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 428–437why, one step back
428
429 pop_indexes = []430 for idx, (item_key, item_value) in enumerate(self._list):431 if item_key == del_key:432 pop_indexes.append(idx)433434 for idx in reversed(pop_indexes):435 del self._list[idx]436437 def __contains__(self, key: typing.Any) -> bool:

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 439–456why, one step back
439 for header_key, header_value in self._list:
440 if header_key == get_header_key:441 return True442 return False443444 def __iter__(self) -> typing.Iterator[typing.Any]:445 return iter(self.keys())446447 def __len__(self) -> int:448 return len(self._list)449450 def __eq__(self, other: typing.Any) -> bool:451 if not isinstance(other, Headers):452 return False453 return sorted(self._list) == sorted(other._list)454455 def __repr__(self) -> str:456 class_name = self.__class__.__name__

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 457–461why, one step back
457
458 encoding_str = ""459 if self.encoding != "ascii":460 encoding_str = f", encoding={self.encoding!r}"461

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 467–474why, one step back
467
468469class Request:470 def __init__(471 self,472 method: str,473 url: typing.Union[str, URL],474 *,

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

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

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 477–479why, one step back
477 headers: HeaderTypes = None,
478 ):479 self.method = method.upper()

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

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

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

lines 481–483why, one step back
481 self.headers = Headers(headers)
482483 if isinstance(data, bytes):

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

lines 485–489why, one step back
485 self.content = data
486 elif isinstance(data, dict):487 self.is_streaming = False488 self.content = urlencode(data, doseq=True).encode("utf-8")489 self.headers["Content-Type"] = "application/x-www-form-urlencoded"

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 490–491why, one step back
490 else:
491 self.is_streaming = True

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 493–497why, one step back
493
494 async def read(self) -> bytes:495 """496 Read and return the response content.497 """

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

line 498why, one step back
498 if not hasattr(self, "content"):

Merge pull request #53 from yunstanford/patch-0Tom Christiebefore adoption21ac95a

line 499why, one step back
499 self.content = b"".join([part async for part in self.stream()])

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

line 500why, one step back
500 return self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 505why, one step back
505 yield part

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 506–507why, one step back
506 elif self.content:
507 yield self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 510–516why, one step back
510 """
511 Adds in any default headers. When using the `Client`, this will512 end up being called into by the `prepare_request()` stage.513514 You can omit this behavior by calling `Client.send()` with an515 explicitly built `Request` instance.516 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 517–524why, one step back
517 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]
518519 has_host = "host" in self.headers520 has_content_length = (521 "content-length" in self.headers or "transfer-encoding" in self.headers522 )523 has_accept_encoding = "accept-encoding" in self.headers524

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 532–538why, one step back
532 auto_headers.append((b"content-length", content_length))
533 if not has_accept_encoding:534 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))535536 for item in reversed(auto_headers):537 self.headers.raw.insert(0, item)538

Still truckin' onTom Christiebefore adoption6cb5c0d

lines 539–541why, one step back
539 def __repr__(self) -> str:
540 class_name = self.__class__.__name__541 url = str(self.url)

Improve class __repr__Tom Christiebefore adoption666d5a8

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 543why, one step back
543

Still truckin' onTom Christiebefore adoption6cb5c0d

line 544why, one step back
544

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 545–549why, one step back
545class Response:
546 def __init__(547 self,548 status_code: int,549 *,

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 550–552why, one step back
550 reason_phrase: str = None,
551 protocol: str = None,552 headers: HeaderTypes = None,

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 554–557why, one step back
554 on_close: typing.Callable = None,
555 request: Request = None,556 history: typing.List["Response"] = None,557 ):

Truckin' onTom Christiebefore adoption6b60d95

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

Still truckin' onTom Christiebefore adoption6cb5c0d

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

Truckin' onTom Christiebefore adoption6b60d95

lines 561–562why, one step back
561 except ValueError:
562 self.status_code = status_code

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 564–566why, one step back
564 self.protocol = protocol
565 self.headers = Headers(headers)566

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 569–570why, one step back
569 self.is_stream_consumed = True
570 self._raw_content = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 571why, one step back
571 else:

Response.contentTom Christiebefore adoption4c55113

lines 572–574why, one step back
572 self.is_closed = False
573 self.is_stream_consumed = False574 self._raw_stream = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 575why, one step back
575

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

response.next()Tom Christiebefore adoptiond652479

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 580–582why, one step back
580
581 @property582 def url(self) -> typing.Optional[URL]:

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 583–587why, one step back
583 """
584 Returns the URL for which the request was made.585586 Requires that `request` was provided when instantiating the response.587 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 589–590why, one step back
589
590 @property

Response.contentTom Christiebefore adoption4c55113

lines 591–593why, one step back
591 def content(self) -> bytes:
592 if not hasattr(self, "_content"):593 if hasattr(self, "_raw_content"):

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 594–596why, one step back
594 content = self.decoder.decode(self._raw_content)
595 content += self.decoder.flush()596 self._content = content

Response.contentTom Christiebefore adoption4c55113

lines 597–599why, one step back
597 else:
598 raise ResponseNotRead()599 return self._content

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 600–635why, one step back
600
601 @property602 def text(self) -> str:603 if not hasattr(self, "_text"):604 content = self.content605 if not content:606 self._text = ""607 else:608 encoding = self.encoding609 self._text = content.decode(encoding, errors="replace")610 return self._text611612 @property613 def encoding(self) -> str:614 if not hasattr(self, "_encoding"):615 encoding = self.charset_encoding616 if encoding is None or not is_known_encoding(encoding):617 encoding = self.apparent_encoding618 if encoding is None or not is_known_encoding(encoding):619 encoding = "utf-8"620 self._encoding = encoding621 return self._encoding622623 @encoding.setter624 def encoding(self, value: str) -> None:625 self._encoding = value626627 @property628 def charset_encoding(self) -> typing.Optional[str]:629 """630 Return the encoding, as specified by the Content-Type header.631 """632 content_type = self.headers.get("Content-Type")633 if content_type is None:634 return None635

Truckin' onTom Christiebefore adoption0ca1c84

lines 636–640why, one step back
636 parsed = cgi.parse_header(content_type)
637 media_type, params = parsed[0], parsed[-1]638 if "charset" in params:639 return params["charset"].strip("'\"")640

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

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

Truckin' onTom Christiebefore adoption0ca1c84

lines 644–647why, one step back
644 if media_type.startswith("text/"):
645 return "iso-8859-1"646647 return None

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 648–654why, one step back
648
649 @property650 def apparent_encoding(self) -> typing.Optional[str]:651 """652 Return the encoding, as it appears to autodetection.653 """654 return chardet.detect(self.content)["encoding"]

Response.contentTom Christiebefore adoption4c55113

lines 655–656why, one step back
655
656 @property

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 657–663why, one step back
657 def decoder(self) -> Decoder:
658 """659 Returns a decoder instance which can be used to decode the raw byte660 content, depending on the Content-Encoding used in the response.661 """662 if not hasattr(self, "_decoder"):663 decoders = [] # type: typing.List[Decoder]

Response.contentTom Christiebefore adoption4c55113

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 665–667why, one step back
665 for value in values:
666 value = value.strip().lower()667 decoder_cls = SUPPORTED_DECODERS[value]

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 668–677why, one step back
668 decoders.append(decoder_cls())
669670 if len(decoders) == 1:671 self._decoder = decoders[0]672 elif len(decoders) > 1:673 self._decoder = MultiDecoder(decoders)674 else:675 self._decoder = IdentityDecoder()676677 return self._decoder

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 678–682why, one step back
678
679 async def read(self) -> bytes:680 """681 Read and return the response content.682 """

Response.contentTom Christiebefore adoption4c55113

line 683why, one step back
683 if not hasattr(self, "_content"):

Merge pull request #53 from yunstanford/patch-0Tom Christiebefore adoption21ac95a

line 684why, one step back
684 self._content = b"".join([part async for part in self.stream()])

Response.contentTom Christiebefore adoption4c55113

line 685why, one step back
685 return self._content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 686–691why, one step back
686
687 async def stream(self) -> typing.AsyncIterator[bytes]:688 """689 A byte-iterator over the decoded response content.690 This allows us to handle gzip, deflate, and brotli encoded responses.691 """

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 694–702why, one step back
694 else:
695 async for chunk in self.raw():696 yield self.decoder.decode(chunk)697 yield self.decoder.flush()698699 async def raw(self) -> typing.AsyncIterator[bytes]:700 """701 A byte-iterator over the raw response content.702 """

Response.contentTom Christiebefore adoption4c55113

lines 703–714why, one step back
703 if hasattr(self, "_raw_content"):
704 yield self._raw_content705 else:706 if self.is_stream_consumed:707 raise StreamConsumed()708 if self.is_closed:709 raise ResponseClosed()710711 self.is_stream_consumed = True712 async for part in self._raw_stream:713 yield part714 await self.close()

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 715–728why, one step back
715
716 async def close(self) -> None:717 """718 Close the response and release the connection.719 Automatically called if the response body is read to completion.720 """721 if not self.is_closed:722 self.is_closed = True723 if self.on_close is not None:724 await self.on_close()725726 @property727 def is_redirect(self) -> bool:728 return (

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 729–730why, one step back
729 self.status_code
730 in (

Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369

lines 731–735why, one step back
731 codes.MOVED_PERMANENTLY,
732 codes.FOUND,733 codes.SEE_OTHER,734 codes.TEMPORARY_REDIRECT,735 codes.PERMANENT_REDIRECT,

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 736–737why, one step back
736 )
737 and "location" in self.headers

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 738why, one step back
738 )

Still truckin' onTom Christiebefore adoption6cb5c0d

line 739why, one step back
739

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

lines 740–757why, one step back
740 def raise_for_status(self) -> None:
741 """742 Raise the `HttpError` if one occurred.743 """744 message = (745 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"746 "For more information check: https://httpstatuses.com/{0.status_code}"747 )748749 if 400 <= self.status_code < 500:750 message = message.format(self, error_type="Client Error")751 elif 500 <= self.status_code < 600:752 message = message.format(self, error_type="Server Error")753 else:754 message = ""755756 if message:757 raise HttpError(message)

Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0

lines 758–759why, one step back
758
759 def __repr__(self) -> str:

repr change: <SyncResponse ...> -> <Response ...>Tom Christiebefore adoption73d5fca

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

Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0

lines 761–823why, one step back
761
762763class SyncResponse:764 """765 A thread-synchronous response. This class proxies onto a `Response`766 instance, providing standard synchronous interfaces where required.767 """768769 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):770 self._response = response771 self._loop = loop772773 @property774 def status_code(self) -> int:775 return self._response.status_code776777 @property778 def reason_phrase(self) -> str:779 return self._response.reason_phrase780781 @property782 def protocol(self) -> typing.Optional[str]:783 return self._response.protocol784785 @property786 def url(self) -> typing.Optional[URL]:787 return self._response.url788789 @property790 def request(self) -> typing.Optional[Request]:791 return self._response.request792793 @property794 def headers(self) -> Headers:795 return self._response.headers796797 @property798 def content(self) -> bytes:799 return self._response.content800801 @property802 def text(self) -> str:803 return self._response.text804805 @property806 def encoding(self) -> str:807 return self._response.encoding808809 @property810 def is_redirect(self) -> bool:811 return self._response.is_redirect812813 def raise_for_status(self) -> None:814 return self._response.raise_for_status()815816 def read(self) -> bytes:817 return self._loop.run_until_complete(self._response.read())818819 def stream(self) -> typing.Iterator[bytes]:820 inner = self._response.stream()821 while True:822 try:823 yield self._loop.run_until_complete(inner.__anext__())

Include URL.__hash__ in test (#64)Yeray Diaz Diazbefore adoption2e9ab2e

line 824why, one step back
824 except StopAsyncIteration:

Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0

lines 825–831why, one step back
825 break
826827 def raw(self) -> typing.Iterator[bytes]:828 inner = self._response.raw()829 while True:830 try:831 yield self._loop.run_until_complete(inner.__anext__())

Include URL.__hash__ in test (#64)Yeray Diaz Diazbefore adoption2e9ab2e

line 832why, one step back
832 except StopAsyncIteration:

Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0

lines 833–836why, one step back
833 break
834835 def close(self) -> None:836 return self._loop.run_until_complete(self._response.close())

Merge pull request #56 from yeraydiazdiaz/test-additional-http-methodsTom Christiebefore adoption87cab4c

lines 837–838why, one step back
837
838 def __repr__(self) -> str:

repr change: <SyncResponse ...> -> <Response ...>Tom Christiebefore adoption73d5fca

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