Skip to content
Myr

models.py

This file

Path

httpcore/models.py

824 lines · 25.2 KiB · Python

Last changed by

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

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

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

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

Finessing interfaceTom Christiebefore adoptiond7619a9

line 47why, one step back
47

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

line 48why, one step back
48ResponseContent = typing.Union[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
50

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 51why, one step back
51class URL:

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

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Finessing interfaceTom Christiebefore adoptiond7619a9

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Fix docstringsTom Christiebefore adoption8a227c1

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

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

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

lines 108–115why, one step back
108 def path(self) -> str:
109 return self.components.path or "/"110111 @property112 def query(self) -> str:113 return self.components.query or ""114115 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 120–122why, one step back
120 return path
121122 @property

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

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 143–146why, one step back
143 def is_relative_url(self) -> bool:
144 return not self.is_absolute_url145146 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Fix docstringsTom Christiebefore adoption8a227c1

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 161why, one step back
161

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 162–168why, one step back
162 def __hash__(self) -> int:
163 return hash(str(self))164165 def __eq__(self, other: typing.Any) -> bool:166 return isinstance(other, URL) and str(self) == str(other)167168 def __str__(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 170–177why, one step back
170
171 def __repr__(self) -> str:172 class_name = self.__class__.__name__173 url_str = str(self)174 return f"{class_name}({url_str!r})"175176177class Origin:

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

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 194–197why, one step back
194 and self.port == other.port
195 )196197 def __hash__(self) -> int:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 199–200why, one step back
199
200

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

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

Improve class __repr__Tom Christiebefore adoption666d5a8

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

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

lines 206–269why, one step back
206 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:
207 assert len(args) < 2, "Too many arguments."208 assert not (args and kwargs), "Cannot mix named and unnamed arguments."209210 value = args[0] if args else kwargs211212 if isinstance(value, str):213 items = parse_qsl(value)214 elif isinstance(value, QueryParams):215 items = value.multi_items()216 elif isinstance(value, list):217 items = value218 else:219 items = value.items() # type: ignore220221 self._list = [(str(k), str(v)) for k, v in items]222 self._dict = {str(k): str(v) for k, v in items}223224 def getlist(self, key: typing.Any) -> typing.List[str]:225 return [item_value for item_key, item_value in self._list if item_key == key]226227 def keys(self) -> typing.KeysView:228 return self._dict.keys()229230 def values(self) -> typing.ValuesView:231 return self._dict.values()232233 def items(self) -> typing.ItemsView:234 return self._dict.items()235236 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:237 return list(self._list)238239 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:240 if key in self._dict:241 return self._dict[key]242 return default243244 def __getitem__(self, key: typing.Any) -> str:245 return self._dict[key]246247 def __contains__(self, key: typing.Any) -> bool:248 return key in self._dict249250 def __iter__(self) -> typing.Iterator[typing.Any]:251 return iter(self.keys())252253 def __len__(self) -> int:254 return len(self._dict)255256 def __eq__(self, other: typing.Any) -> bool:257 if not isinstance(other, self.__class__):258 return False259 return sorted(self._list) == sorted(other._list)260261 def __str__(self) -> str:262 return urlencode(self._list)263264 def __repr__(self) -> str:265 class_name = self.__class__.__name__266 query_string = str(self)267 return f"{class_name}({query_string!r})"268269

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 289why, one step back
289 ]

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

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

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 297–321why, one step back
297 """
298 if self._encoding is None:299 for encoding in ["ascii", "utf-8"]:300 for key, value in self.raw:301 try:302 key.decode(encoding)303 value.decode(encoding)304 except UnicodeDecodeError:305 break306 else:307 # The else block runs if 'break' did not occur, meaning308 # all values fitted the encoding.309 self._encoding = encoding310 break311 else:312 # The ISO-8859-1 encoding covers all 256 code points in a byte,313 # so will never raise decode errors.314 self._encoding = "iso-8859-1"315 return self._encoding316317 @encoding.setter318 def encoding(self, value: str) -> None:319 self._encoding = value320321 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 355–358why, one step back
355 for item_key, item_value in self._list
356 if item_key == get_header_key357 ]358

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 393–411why, one step back
393
394 found_indexes = []395 for idx, (item_key, item_value) in enumerate(self._list):396 if item_key == set_key:397 found_indexes.append(idx)398399 for idx in reversed(found_indexes[1:]):400 del self._list[idx]401402 if found_indexes:403 idx = found_indexes[0]404 self._list[idx] = (set_key, set_value)405 else:406 self._list.append((set_key, set_value))407408 def __delitem__(self, key: str) -> None:409 """410 Remove the header `key`.411 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 424–441why, one step back
424 for header_key, header_value in self._list:
425 if header_key == get_header_key:426 return True427 return False428429 def __iter__(self) -> typing.Iterator[typing.Any]:430 return iter(self.keys())431432 def __len__(self) -> int:433 return len(self._list)434435 def __eq__(self, other: typing.Any) -> bool:436 if not isinstance(other, Headers):437 return False438 return sorted(self._list) == sorted(other._list)439440 def __repr__(self) -> str:441 class_name = self.__class__.__name__

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

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

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

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

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

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

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 490why, one step back
490 yield part

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 491–492why, one step back
491 elif self.content:
492 yield self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 495–501why, one step back
495 """
496 Adds in any default headers. When using the `Client`, this will497 end up being called into by the `prepare_request()` stage.498499 You can omit this behavior by calling `Client.send()` with an500 explicitly built `Request` instance.501 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 502–509why, one step back
502 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]
503504 has_host = "host" in self.headers505 has_content_length = (506 "content-length" in self.headers or "transfer-encoding" in self.headers507 )508 has_accept_encoding = "accept-encoding" in self.headers509

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Still truckin' onTom Christiebefore adoption6cb5c0d

lines 524–526why, one step back
524 def __repr__(self) -> str:
525 class_name = self.__class__.__name__526 url = str(self.url)

Improve class __repr__Tom Christiebefore adoption666d5a8

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 528why, one step back
528

Still truckin' onTom Christiebefore adoption6cb5c0d

line 529why, one step back
529

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Finessing interfaceTom Christiebefore adoptiond7619a9

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

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Truckin' onTom Christiebefore adoption6b60d95

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

Still truckin' onTom Christiebefore adoption6cb5c0d

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

Truckin' onTom Christiebefore adoption6b60d95

lines 546–547why, one step back
546 except ValueError:
547 self.status_code = status_code

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 554–555why, one step back
554 self.is_stream_consumed = True
555 self._raw_content = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 556why, one step back
556 else:

Response.contentTom Christiebefore adoption4c55113

lines 557–559why, one step back
557 self.is_closed = False
558 self.is_stream_consumed = False559 self._raw_stream = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 560why, one step back
560

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

response.next()Tom Christiebefore adoptiond652479

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 565–567why, one step back
565
566 @property567 def url(self) -> typing.Optional[URL]:

Clean up response interfaceTom Christiebefore adoption4d908d0

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 574–575why, one step back
574
575 @property

Response.contentTom Christiebefore adoption4c55113

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

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

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

Response.contentTom Christiebefore adoption4c55113

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

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 585–620why, one step back
585
586 @property587 def text(self) -> str:588 if not hasattr(self, "_text"):589 content = self.content590 if not content:591 self._text = ""592 else:593 encoding = self.encoding594 self._text = content.decode(encoding, errors="replace")595 return self._text596597 @property598 def encoding(self) -> str:599 if not hasattr(self, "_encoding"):600 encoding = self.charset_encoding601 if encoding is None or not is_known_encoding(encoding):602 encoding = self.apparent_encoding603 if encoding is None or not is_known_encoding(encoding):604 encoding = "utf-8"605 self._encoding = encoding606 return self._encoding607608 @encoding.setter609 def encoding(self, value: str) -> None:610 self._encoding = value611612 @property613 def charset_encoding(self) -> typing.Optional[str]:614 """615 Return the encoding, as specified by the Content-Type header.616 """617 content_type = self.headers.get("Content-Type")618 if content_type is None:619 return None620

Truckin' onTom Christiebefore adoption0ca1c84

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

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

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

Truckin' onTom Christiebefore adoption0ca1c84

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

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

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

Response.contentTom Christiebefore adoption4c55113

lines 640–641why, one step back
640
641 @property

Clean up response interfaceTom Christiebefore adoption4d908d0

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

Response.contentTom Christiebefore adoption4c55113

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 653–662why, one step back
653 decoders.append(decoder_cls())
654655 if len(decoders) == 1:656 self._decoder = decoders[0]657 elif len(decoders) > 1:658 self._decoder = MultiDecoder(decoders)659 else:660 self._decoder = IdentityDecoder()661662 return self._decoder

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

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

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

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

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 714–715why, one step back
714 self.status_code
715 in (

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

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

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 721–722why, one step back
721 )
722 and "location" in self.headers

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 723why, one step back
723 )

Still truckin' onTom Christiebefore adoption6cb5c0d

line 724why, one step back
724

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

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

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

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

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

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

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

lines 746–808why, one step back
746
747748class SyncResponse:749 """750 A thread-synchronous response. This class proxies onto a `Response`751 instance, providing standard synchronous interfaces where required.752 """753754 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):755 self._response = response756 self._loop = loop757758 @property759 def status_code(self) -> int:760 return self._response.status_code761762 @property763 def reason_phrase(self) -> str:764 return self._response.reason_phrase765766 @property767 def protocol(self) -> typing.Optional[str]:768 return self._response.protocol769770 @property771 def url(self) -> typing.Optional[URL]:772 return self._response.url773774 @property775 def request(self) -> typing.Optional[Request]:776 return self._response.request777778 @property779 def headers(self) -> Headers:780 return self._response.headers781782 @property783 def content(self) -> bytes:784 return self._response.content785786 @property787 def text(self) -> str:788 return self._response.text789790 @property791 def encoding(self) -> str:792 return self._response.encoding793794 @property795 def is_redirect(self) -> bool:796 return self._response.is_redirect797798 def raise_for_status(self) -> None:799 return self._response.raise_for_status()800801 def read(self) -> bytes:802 return self._loop.run_until_complete(self._response.read())803804 def stream(self) -> typing.Iterator[bytes]:805 inner = self._response.stream()806 while True:807 try:808 yield self._loop.run_until_complete(inner.__anext__())

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

line 809why, one step back
809 except StopAsyncIteration:

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

lines 810–816why, one step back
810 break
811812 def raw(self) -> typing.Iterator[bytes]:813 inner = self._response.raw()814 while True:815 try:816 yield self._loop.run_until_complete(inner.__anext__())

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

line 817why, one step back
817 except StopAsyncIteration:

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

lines 818–821why, one step back
818 break
819820 def close(self) -> None:821 return self._loop.run_until_complete(self._response.close())

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

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

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

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