Skip to content
Myr

models.py

This file

Path

httpcore/models.py

826 lines · 25.3 KiB · Python

Last changed by

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

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

line 7why, one step back
7import idna

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 8why, one step back
8import rfc3986

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

line 9why, one step back
9

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 10–17why, one step back
10from .config import SSLConfig, TimeoutConfig
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)

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

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

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 32why, one step back
32

Finessing interfaceTom Christiebefore adoptiond7619a9

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 34why, one step back
34

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

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

Finessing interfaceTom Christiebefore adoptiond7619a9

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

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

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

Finessing interfaceTom Christiebefore adoptiond7619a9

line 49why, one step back
49

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

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

Finessing interfaceTom Christiebefore adoptiond7619a9

line 51why, one step back
51

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

line 52why, one step back
52

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 53why, one step back
53class URL:

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

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Finessing interfaceTom Christiebefore adoptiond7619a9

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Fix docstringsTom Christiebefore adoption8a227c1

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

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

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 101–106why, one step back
101
102 @property103 def port(self) -> int:104 port = self.components.port105 if port is None:106 return {"https": 443, "http": 80}[self.scheme]

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

lines 110–117why, one step back
110 def path(self) -> str:
111 return self.components.path or "/"112113 @property114 def query(self) -> str:115 return self.components.query or ""116117 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 122–124why, one step back
122 return path
123124 @property

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

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 130–132why, one step back
130 return self.components.scheme == "https"
131132 @property

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 145–148why, one step back
145 def is_relative_url(self) -> bool:
146 return not self.is_absolute_url147148 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Fix docstringsTom Christiebefore adoption8a227c1

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 163why, one step back
163

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 172–179why, one step back
172
173 def __repr__(self) -> str:174 class_name = self.__class__.__name__175 url_str = str(self)176 return f"{class_name}({url_str!r})"177178179class Origin:

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

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 196–199why, one step back
196 and self.port == other.port
197 )198199 def __hash__(self) -> int:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 201–202why, one step back
201
202

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

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

Improve class __repr__Tom Christiebefore adoption666d5a8

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

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

lines 208–271why, one step back
208 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:
209 assert len(args) < 2, "Too many arguments."210 assert not (args and kwargs), "Cannot mix named and unnamed arguments."211212 value = args[0] if args else kwargs213214 if isinstance(value, str):215 items = parse_qsl(value)216 elif isinstance(value, QueryParams):217 items = value.multi_items()218 elif isinstance(value, list):219 items = value220 else:221 items = value.items() # type: ignore222223 self._list = [(str(k), str(v)) for k, v in items]224 self._dict = {str(k): str(v) for k, v in items}225226 def getlist(self, key: typing.Any) -> typing.List[str]:227 return [item_value for item_key, item_value in self._list if item_key == key]228229 def keys(self) -> typing.KeysView:230 return self._dict.keys()231232 def values(self) -> typing.ValuesView:233 return self._dict.values()234235 def items(self) -> typing.ItemsView:236 return self._dict.items()237238 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:239 return list(self._list)240241 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:242 if key in self._dict:243 return self._dict[key]244 return default245246 def __getitem__(self, key: typing.Any) -> str:247 return self._dict[key]248249 def __contains__(self, key: typing.Any) -> bool:250 return key in self._dict251252 def __iter__(self) -> typing.Iterator[typing.Any]:253 return iter(self.keys())254255 def __len__(self) -> int:256 return len(self._dict)257258 def __eq__(self, other: typing.Any) -> bool:259 if not isinstance(other, self.__class__):260 return False261 return sorted(self._list) == sorted(other._list)262263 def __str__(self) -> str:264 return urlencode(self._list)265266 def __repr__(self) -> str:267 class_name = self.__class__.__name__268 query_string = str(self)269 return f"{class_name}({query_string!r})"270271

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 291why, one step back
291 ]

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

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

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 299–323why, one step back
299 """
300 if self._encoding is None:301 for encoding in ["ascii", "utf-8"]:302 for key, value in self.raw:303 try:304 key.decode(encoding)305 value.decode(encoding)306 except UnicodeDecodeError:307 break308 else:309 # The else block runs if 'break' did not occur, meaning310 # all values fitted the encoding.311 self._encoding = encoding312 break313 else:314 # The ISO-8859-1 encoding covers all 256 code points in a byte,315 # so will never raise decode errors.316 self._encoding = "iso-8859-1"317 return self._encoding318319 @encoding.setter320 def encoding(self, value: str) -> None:321 self._encoding = value322323 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 357–360why, one step back
357 for item_key, item_value in self._list
358 if item_key == get_header_key359 ]360

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 370–378why, one step back
370 """
371 Return a single header value.372373 If there are multiple headers with the same key, then we concatenate374 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2375 """376 normalized_key = key.lower().encode(self.encoding)377378 items = []

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 395–413why, one step back
395
396 found_indexes = []397 for idx, (item_key, item_value) in enumerate(self._list):398 if item_key == set_key:399 found_indexes.append(idx)400401 for idx in reversed(found_indexes[1:]):402 del self._list[idx]403404 if found_indexes:405 idx = found_indexes[0]406 self._list[idx] = (set_key, set_value)407 else:408 self._list.append((set_key, set_value))409410 def __delitem__(self, key: str) -> None:411 """412 Remove the header `key`.413 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 426–443why, one step back
426 for header_key, header_value in self._list:
427 if header_key == get_header_key:428 return True429 return False430431 def __iter__(self) -> typing.Iterator[typing.Any]:432 return iter(self.keys())433434 def __len__(self) -> int:435 return len(self._list)436437 def __eq__(self, other: typing.Any) -> bool:438 if not isinstance(other, Headers):439 return False440 return sorted(self._list) == sorted(other._list)441442 def __repr__(self) -> str:443 class_name = self.__class__.__name__

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

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

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

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

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

lines 468–470why, one step back
468 self.headers = Headers(headers)
469470 if isinstance(data, bytes):

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

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

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 492why, one step back
492 yield part

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 493–494why, one step back
493 elif self.content:
494 yield self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 504–511why, one step back
504 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]
505506 has_host = "host" in self.headers507 has_content_length = (508 "content-length" in self.headers or "transfer-encoding" in self.headers509 )510 has_accept_encoding = "accept-encoding" in self.headers511

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Still truckin' onTom Christiebefore adoption6cb5c0d

lines 526–528why, one step back
526 def __repr__(self) -> str:
527 class_name = self.__class__.__name__528 url = str(self.url)

Improve class __repr__Tom Christiebefore adoption666d5a8

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 530why, one step back
530

Still truckin' onTom Christiebefore adoption6cb5c0d

line 531why, one step back
531

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Finessing interfaceTom Christiebefore adoptiond7619a9

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

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Truckin' onTom Christiebefore adoption6b60d95

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

Still truckin' onTom Christiebefore adoption6cb5c0d

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

Truckin' onTom Christiebefore adoption6b60d95

lines 548–549why, one step back
548 except ValueError:
549 self.status_code = status_code

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 556–557why, one step back
556 self.is_stream_consumed = True
557 self._raw_content = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 558why, one step back
558 else:

Response.contentTom Christiebefore adoption4c55113

lines 559–561why, one step back
559 self.is_closed = False
560 self.is_stream_consumed = False561 self._raw_stream = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 562why, one step back
562

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

response.next()Tom Christiebefore adoptiond652479

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 567–569why, one step back
567
568 @property569 def url(self) -> typing.Optional[URL]:

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 570–574why, one step back
570 """
571 Returns the URL for which the request was made.572573 Requires that `request` was provided when instantiating the response.574 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 576–577why, one step back
576
577 @property

Response.contentTom Christiebefore adoption4c55113

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

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

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

Response.contentTom Christiebefore adoption4c55113

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

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 587–622why, one step back
587
588 @property589 def text(self) -> str:590 if not hasattr(self, "_text"):591 content = self.content592 if not content:593 self._text = ""594 else:595 encoding = self.encoding596 self._text = content.decode(encoding, errors="replace")597 return self._text598599 @property600 def encoding(self) -> str:601 if not hasattr(self, "_encoding"):602 encoding = self.charset_encoding603 if encoding is None or not is_known_encoding(encoding):604 encoding = self.apparent_encoding605 if encoding is None or not is_known_encoding(encoding):606 encoding = "utf-8"607 self._encoding = encoding608 return self._encoding609610 @encoding.setter611 def encoding(self, value: str) -> None:612 self._encoding = value613614 @property615 def charset_encoding(self) -> typing.Optional[str]:616 """617 Return the encoding, as specified by the Content-Type header.618 """619 content_type = self.headers.get("Content-Type")620 if content_type is None:621 return None622

Truckin' onTom Christiebefore adoption0ca1c84

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

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

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

Truckin' onTom Christiebefore adoption0ca1c84

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

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

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

Response.contentTom Christiebefore adoption4c55113

lines 642–643why, one step back
642
643 @property

Clean up response interfaceTom Christiebefore adoption4d908d0

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

Response.contentTom Christiebefore adoption4c55113

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 655–664why, one step back
655 decoders.append(decoder_cls())
656657 if len(decoders) == 1:658 self._decoder = decoders[0]659 elif len(decoders) > 1:660 self._decoder = MultiDecoder(decoders)661 else:662 self._decoder = IdentityDecoder()663664 return self._decoder

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

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

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

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

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 690–701why, one step back
690 if hasattr(self, "_raw_content"):
691 yield self._raw_content692 else:693 if self.is_stream_consumed:694 raise StreamConsumed()695 if self.is_closed:696 raise ResponseClosed()697698 self.is_stream_consumed = True699 async for part in self._raw_stream:700 yield part701 await self.close()

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 716–717why, one step back
716 self.status_code
717 in (

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

lines 718–722why, one step back
718 codes.MOVED_PERMANENTLY,
719 codes.FOUND,720 codes.SEE_OTHER,721 codes.TEMPORARY_REDIRECT,722 codes.PERMANENT_REDIRECT,

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 723–724why, one step back
723 )
724 and "location" in self.headers

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 725why, one step back
725 )

Still truckin' onTom Christiebefore adoption6cb5c0d

line 726why, one step back
726

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

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

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

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

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

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

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

lines 748–823why, one step back
748
749750class SyncResponse:751 """752 A thread-synchronous response. This class proxies onto a `Response`753 instance, providing standard synchronous interfaces where required.754 """755756 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):757 self._response = response758 self._loop = loop759760 @property761 def status_code(self) -> int:762 return self._response.status_code763764 @property765 def reason_phrase(self) -> str:766 return self._response.reason_phrase767768 @property769 def protocol(self) -> typing.Optional[str]:770 return self._response.protocol771772 @property773 def url(self) -> typing.Optional[URL]:774 return self._response.url775776 @property777 def request(self) -> typing.Optional[Request]:778 return self._response.request779780 @property781 def headers(self) -> Headers:782 return self._response.headers783784 @property785 def content(self) -> bytes:786 return self._response.content787788 @property789 def text(self) -> str:790 return self._response.text791792 @property793 def encoding(self) -> str:794 return self._response.encoding795796 @property797 def is_redirect(self) -> bool:798 return self._response.is_redirect799800 def raise_for_status(self) -> None:801 return self._response.raise_for_status()802803 def read(self) -> bytes:804 return self._loop.run_until_complete(self._response.read())805806 def stream(self) -> typing.Iterator[bytes]:807 inner = self._response.stream()808 while True:809 try:810 yield self._loop.run_until_complete(inner.__anext__())811 except StopAsyncIteration as exc:812 break813814 def raw(self) -> typing.Iterator[bytes]:815 inner = self._response.raw()816 while True:817 try:818 yield self._loop.run_until_complete(inner.__anext__())819 except StopAsyncIteration as exc:820 break821822 def close(self) -> None:823 return self._loop.run_until_complete(self._response.close())

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

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

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

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