Skip to content
Myr

models.py

This file

Path

httpcore/models.py

608 lines · 19.0 KiB · Python

Last changed by

Add idna support. More tests.Tom Christiebefore adoptionb948798

History of this file

Take it

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

line 1why, one step back
1import cgi

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 2–3why, one step back
2import typing
3

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

line 4why, one step back
4import chardet

Add idna support. More tests.Tom Christiebefore adoptionb948798

line 5why, one step back
5import idna

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 6why, one step back
6import rfc3986

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

line 7why, one step back
7

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 16why, one step back
16from .exceptions import InvalidURL, ResponseClosed, ResponseNotRead, StreamConsumed

Finessing interfaceTom Christiebefore adoptiond7619a9

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

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 18–23why, one step back
18from .utils import (
19 get_reason_phrase,20 is_known_encoding,21 normalize_header_key,22 normalize_header_value,23)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 24why, one step back
24

Finessing interfaceTom Christiebefore adoptiond7619a9

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 26why, one step back
26

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 27–32why, one step back
27HeaderTypes = typing.Union[
28 "Headers",29 typing.Dict[typing.AnyStr, typing.AnyStr],30 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],31]32

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

line 33why, one step back
33ByteOrByteStream = typing.Union[bytes, typing.AsyncIterator[bytes]]

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 34–35why, one step back
34
35

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 36why, one step back
36class URL:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 37why, one step back
37 def __init__(self, url: URLTypes, allow_relative: bool = False) -> None:

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 42–44why, one step back
42 else:
43 self.components = url.components44

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 45–54why, one step back
45 # Handle IDNA domain names.
46 if self.components.authority:47 idna_authority = self.components.authority.encode("idna").decode("ascii")48 if idna_authority != self.components.authority:49 self.components = self.components.copy_with(authority=idna_authority)5051 # Normalize schema and domain name.52 self.components = self.components.normalize()5354 # Enforce absolute URLs by default.

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 55–60why, one step back
55 if not allow_relative:
56 if not self.scheme:57 raise InvalidURL("No scheme included in URL.")58 if self.scheme not in ("http", "https"):59 raise InvalidURL('URL scheme must be "http" or "https".')60 if not self.host:

Add idna support. More tests.Tom Christiebefore adoptionb948798

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 62–64why, one step back
62
63 @property64 def scheme(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 66–67why, one step back
66
67 @property

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 70–72why, one step back
70
71 @property72 def path(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 73why, one step back
73 return self.components.path or "/"

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 74–76why, one step back
74
75 @property76 def query(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 77why, one step back
77 return self.components.query or ""

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 78–80why, one step back
78
79 @property80 def fragment(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 81why, one step back
81 return self.components.fragment or ""

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 82–83why, one step back
82
83 @property

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 86–106why, one step back
86
87 @property88 def port(self) -> int:89 port = self.components.port90 if port is None:91 return {"https": 443, "http": 80}[self.scheme]92 return port9394 @property95 def full_path(self) -> str:96 path = self.path or "/"97 query = self.query98 if query:99 return path + "?" + query100 return path101102 @property103 def is_secure(self) -> bool:104 return self.components.scheme == "https"105106 @property

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 107–116why, one step back
107 def is_absolute_url(self) -> bool:
108 """109 Return `True` for absolute URLs such as 'http://example.com/path',110 and `False` for relative URLs such as '/path'.111 """112 # We don't use rfc3986's `is_absolute` because it treats113 # URLs with a fragment portion as not absolute.114 # What we actually care about is if the URL provides115 # a scheme and hostname to which connections should be made.116 return self.components.scheme and self.components.host

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 117–118why, one step back
117
118 @property

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 119–122why, one step back
119 def is_relative_url(self) -> bool:
120 return not self.is_absolute_url121122 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 123–125why, one step back
123 def origin(self) -> "Origin":
124 return Origin(self)125

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 126–129why, one step back
126 def copy_with(self, **kwargs: typing.Any) -> "URL":
127 return URL(self.components.copy_with(**kwargs))128129 def resolve_with(self, base_url: URLTypes) -> "URL":

Add idna support. More tests.Tom Christiebefore adoptionb948798

lines 130–137why, one step back
130 """
131 Return an absolute URL, using base_url as the base.132 """133 # We drop any fragment portion, because RFC 3986 strictly134 # treats URLs with a fragment portion as not being absolute URLs,135 # but we want to treat them as such for the purposes of136 base_url = URL(base_url).copy_with(fragment=None)137 return URL(self.components.resolve_with(base_url.components))

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 138why, one step back
138

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 139–145why, one step back
139 def __hash__(self) -> int:
140 return hash(str(self))141142 def __eq__(self, other: typing.Any) -> bool:143 return isinstance(other, URL) and str(self) == str(other)144145 def __str__(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 147–154why, one step back
147
148 def __repr__(self) -> str:149 class_name = self.__class__.__name__150 url_str = str(self)151 return f"{class_name}({url_str!r})"152153154class Origin:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 157–158why, one step back
157 url = URL(url)
158 self.is_ssl = url.scheme == "https"

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 160–165why, one step back
160 self.port = url.port
161162 def __eq__(self, other: typing.Any) -> bool:163 return (164 isinstance(other, self.__class__)165 and self.is_ssl == other.is_ssl

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 167–170why, one step back
167 and self.port == other.port
168 )169170 def __hash__(self) -> int:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 172–178why, one step back
172
173174class Headers(typing.MutableMapping[str, str]):175 """176 A case-insensitive multidict.177 """178

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 180–185why, one step back
180 if headers is None:
181 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]182 elif isinstance(headers, Headers):183 self._list = list(headers.raw)184 elif isinstance(headers, dict):185 self._list = [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 187–190why, one step back
187 for k, v in headers.items()
188 ]189 else:190 self._list = [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 193why, one step back
193 ]

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 195–196why, one step back
195
196 @property

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 197–225why, one step back
197 def encoding(self) -> str:
198 """199 Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be200 seen in the wild.201 """202 if self._encoding is None:203 for encoding in ["ascii", "utf-8"]:204 for key, value in self.raw:205 try:206 key.decode(encoding)207 value.decode(encoding)208 except UnicodeDecodeError:209 break210 else:211 # The else block runs if 'break' did not occur, meaning212 # all values fitted the encoding.213 self._encoding = encoding214 break215 else:216 # The ISO-8859-1 encoding covers all 256 code points in a byte,217 # so will never raise decode errors.218 self._encoding = "iso-8859-1"219 return self._encoding220221 @encoding.setter222 def encoding(self, value: str) -> None:223 self._encoding = value224225 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 227–230why, one step back
227 """
228 Returns a list of the raw header items, as byte pairs.229 May be mutated in-place.230 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 238–240why, one step back
238
239 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore240 return [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 242–250why, one step back
242 for key, value in self._list
243 ]244245 def get(self, key: str, default: typing.Any = None) -> typing.Any:246 try:247 return self[key]248 except KeyError:249 return default250

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 252–258why, one step back
252 """
253 Return multiple header values.254 """255 get_header_key = key.lower().encode(self.encoding)256257 values = [258 item_value.decode(self.encoding)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 259–262why, one step back
259 for item_key, item_value in self._list
260 if item_key == get_header_key261 ]262

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 263–270why, one step back
263 if not split_commas:
264 return values265266 split_values = []267 for value in values:268 split_values.extend([item.strip() for item in value.split(",")])269 return split_values270

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 272–280why, one step back
272 """
273 Return a single header value.274275 If there are multiple headers with the same key, then we concatenate276 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2277 """278 normalized_key = key.lower().encode(self.encoding)279280 items = []

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 282–287why, one step back
282 if header_key == normalized_key:
283 items.append(header_value.decode(self.encoding))284285 if items:286 return ", ".join(items)287

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 288–294why, one step back
288 raise KeyError(key)
289290 def __setitem__(self, key: str, value: str) -> None:291 """292 Set the header `key` to `value`, removing any duplicate entries.293 Retains insertion order.294 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 297–315why, one step back
297
298 found_indexes = []299 for idx, (item_key, item_value) in enumerate(self._list):300 if item_key == set_key:301 found_indexes.append(idx)302303 for idx in reversed(found_indexes[1:]):304 del self._list[idx]305306 if found_indexes:307 idx = found_indexes[0]308 self._list[idx] = (set_key, set_value)309 else:310 self._list.append((set_key, set_value))311312 def __delitem__(self, key: str) -> None:313 """314 Remove the header `key`.315 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 317–326why, one step back
317
318 pop_indexes = []319 for idx, (item_key, item_value) in enumerate(self._list):320 if item_key == del_key:321 pop_indexes.append(idx)322323 for idx in reversed(pop_indexes):324 del self._list[idx]325326 def __contains__(self, key: typing.Any) -> bool:

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 328–345why, one step back
328 for header_key, header_value in self._list:
329 if header_key == get_header_key:330 return True331 return False332333 def __iter__(self) -> typing.Iterator[typing.Any]:334 return iter(self.keys())335336 def __len__(self) -> int:337 return len(self._list)338339 def __eq__(self, other: typing.Any) -> bool:340 if not isinstance(other, Headers):341 return False342 return sorted(self._list) == sorted(other._list)343344 def __repr__(self) -> str:345 class_name = self.__class__.__name__

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 346–350why, one step back
346
347 encoding_str = ""348 if self.encoding != "ascii":349 encoding_str = f", encoding={self.encoding!r}"350

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 356–364why, one step back
356
357358class Request:359 def __init__(360 self,361 method: str,362 url: typing.Union[str, URL],363 *,364 headers: HeaderTypes = None,

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 366–368why, one step back
366 ):
367 self.method = method.upper()368 self.url = URL(url) if isinstance(url, str) else url

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 372–373why, one step back
372 else:
373 self.is_streaming = True

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 375–380why, one step back
375 self.headers = Headers(headers)
376377 async def read(self) -> bytes:378 """379 Read and return the response content.380 """

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 384–386why, one step back
384 content += part
385 self.content = content386 return self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 391why, one step back
391 yield part

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 392–393why, one step back
392 elif self.content:
393 yield self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 396–402why, one step back
396 """
397 Adds in any default headers. When using the `Client`, this will398 end up being called into by the `prepare_request()` stage.399400 You can omit this behavior by calling `Client.send()` with an401 explicitly built `Request` instance.402 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 403–410why, one step back
403 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]
404405 has_host = "host" in self.headers406 has_content_length = (407 "content-length" in self.headers or "transfer-encoding" in self.headers408 )409 has_accept_encoding = "accept-encoding" in self.headers410

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 418–430why, one step back
418 auto_headers.append((b"content-length", content_length))
419 if not has_accept_encoding:420 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))421422 for item in reversed(auto_headers):423 self.headers.raw.insert(0, item)424425426class Response:427 def __init__(428 self,429 status_code: int,430 *,

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 431–433why, one step back
431 reason_phrase: str = None,
432 protocol: str = None,433 headers: HeaderTypes = None,

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 435–439why, one step back
435 on_close: typing.Callable = None,
436 request: Request = None,437 history: typing.List["Response"] = None,438 ):439 self.status_code = status_code

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 441–443why, one step back
441 self.protocol = protocol
442 self.headers = Headers(headers)443

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 446–447why, one step back
446 self.is_stream_consumed = True
447 self._raw_content = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 448why, one step back
448 else:

Response.contentTom Christiebefore adoption4c55113

lines 449–451why, one step back
449 self.is_closed = False
450 self.is_stream_consumed = False451 self._raw_stream = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 452why, one step back
452

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

response.next()Tom Christiebefore adoptiond652479

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 457–459why, one step back
457
458 @property459 def url(self) -> typing.Optional[URL]:

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 460–464why, one step back
460 """
461 Returns the URL for which the request was made.462463 Requires that `request` was provided when instantiating the response.464 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 466–467why, one step back
466
467 @property

Response.contentTom Christiebefore adoption4c55113

lines 468–470why, one step back
468 def content(self) -> bytes:
469 if not hasattr(self, "_content"):470 if hasattr(self, "_raw_content"):

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 471–473why, one step back
471 content = self.decoder.decode(self._raw_content)
472 content += self.decoder.flush()473 self._content = content

Response.contentTom Christiebefore adoption4c55113

lines 474–476why, one step back
474 else:
475 raise ResponseNotRead()476 return self._content

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 477–521why, one step back
477
478 @property479 def text(self) -> str:480 if not hasattr(self, "_text"):481 content = self.content482 if not content:483 self._text = ""484 else:485 encoding = self.encoding486 self._text = content.decode(encoding, errors="replace")487 return self._text488489 @property490 def encoding(self) -> str:491 if not hasattr(self, "_encoding"):492 encoding = self.charset_encoding493 if encoding is None or not is_known_encoding(encoding):494 encoding = self.apparent_encoding495 if encoding is None or not is_known_encoding(encoding):496 encoding = "utf-8"497 self._encoding = encoding498 return self._encoding499500 @encoding.setter501 def encoding(self, value: str) -> None:502 self._encoding = value503504 @property505 def charset_encoding(self) -> typing.Optional[str]:506 """507 Return the encoding, as specified by the Content-Type header.508 """509 content_type = self.headers.get("Content-Type")510 if content_type is None:511 return None512513 parsed = cgi.parse_header(content_type)[-1]514 return parsed.get("charset")515516 @property517 def apparent_encoding(self) -> typing.Optional[str]:518 """519 Return the encoding, as it appears to autodetection.520 """521 return chardet.detect(self.content)["encoding"]

Response.contentTom Christiebefore adoption4c55113

lines 522–523why, one step back
522
523 @property

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 524–530why, one step back
524 def decoder(self) -> Decoder:
525 """526 Returns a decoder instance which can be used to decode the raw byte527 content, depending on the Content-Encoding used in the response.528 """529 if not hasattr(self, "_decoder"):530 decoders = [] # type: typing.List[Decoder]

Response.contentTom Christiebefore adoption4c55113

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 532–534why, one step back
532 for value in values:
533 value = value.strip().lower()534 decoder_cls = SUPPORTED_DECODERS[value]

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 535–544why, one step back
535 decoders.append(decoder_cls())
536537 if len(decoders) == 1:538 self._decoder = decoders[0]539 elif len(decoders) > 1:540 self._decoder = MultiDecoder(decoders)541 else:542 self._decoder = IdentityDecoder()543544 return self._decoder

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 545–549why, one step back
545
546 async def read(self) -> bytes:547 """548 Read and return the response content.549 """

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 553–555why, one step back
553 content += part
554 self._content = content555 return self._content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 556–561why, one step back
556
557 async def stream(self) -> typing.AsyncIterator[bytes]:558 """559 A byte-iterator over the decoded response content.560 This allows us to handle gzip, deflate, and brotli encoded responses.561 """

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 564–572why, one step back
564 else:
565 async for chunk in self.raw():566 yield self.decoder.decode(chunk)567 yield self.decoder.flush()568569 async def raw(self) -> typing.AsyncIterator[bytes]:570 """571 A byte-iterator over the raw response content.572 """

Response.contentTom Christiebefore adoption4c55113

lines 573–584why, one step back
573 if hasattr(self, "_raw_content"):
574 yield self._raw_content575 else:576 if self.is_stream_consumed:577 raise StreamConsumed()578 if self.is_closed:579 raise ResponseClosed()580581 self.is_stream_consumed = True582 async for part in self._raw_stream:583 yield part584 await self.close()

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 585–598why, one step back
585
586 async def close(self) -> None:587 """588 Close the response and release the connection.589 Automatically called if the response body is read to completion.590 """591 if not self.is_closed:592 self.is_closed = True593 if self.on_close is not None:594 await self.on_close()595596 @property597 def is_redirect(self) -> bool:598 return (

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 599–607why, one step back
599 self.status_code
600 in (601 codes.moved_permanently,602 codes.found,603 codes.see_other,604 codes.temporary_redirect,605 codes.permanent_redirect,606 )607 and "location" in self.headers

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 608why, one step back
608 )