Skip to content
Myr

models.py

This file

Path

httpcore/models.py

580 lines · 17.8 KiB · Python

Last changed by

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

line 5why, one step back
5import rfc3986

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

line 6why, one step back
6

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Finessing interfaceTom Christiebefore adoptiond7619a9

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

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 23why, one step back
23

Finessing interfaceTom Christiebefore adoptiond7619a9

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 25why, one step back
25

Finessing interfaceTom Christiebefore adoptiond7619a9

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 33–34why, one step back
33
34

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 35why, one step back
35class URL:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Finessing interfaceTom Christiebefore adoptiond7619a9

line 37why, one step back
37 if isinstance(url, str):

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 38–40why, one step back
38 self.components = rfc3986.api.uri_reference(url).normalize()
39 elif isinstance(url, rfc3986.uri.URIReference):40 self.components = url

Finessing interfaceTom Christiebefore adoptiond7619a9

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 44–50why, one step back
44 if not allow_relative:
45 if not self.scheme:46 raise InvalidURL("No scheme included in URL.")47 if self.scheme not in ("http", "https"):48 raise InvalidURL('URL scheme must be "http" or "https".')49 if not self.host:50 raise InvalidURL("No hostname included in URL.")

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 51–53why, one step back
51
52 @property53 def scheme(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 55–56why, one step back
55
56 @property

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 59–61why, one step back
59
60 @property61 def path(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 63–65why, one step back
63
64 @property65 def query(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 67–69why, one step back
67
68 @property69 def fragment(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 71–72why, one step back
71
72 @property

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 75–95why, one step back
75
76 @property77 def port(self) -> int:78 port = self.components.port79 if port is None:80 return {"https": 443, "http": 80}[self.scheme]81 return port8283 @property84 def full_path(self) -> str:85 path = self.path or "/"86 query = self.query87 if query:88 return path + "?" + query89 return path9091 @property92 def is_secure(self) -> bool:93 return self.components.scheme == "https"9495 @property

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 96–99why, one step back
96 def is_absolute(self) -> bool:
97 return self.components.is_absolute()9899 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 100–102why, one step back
100 def origin(self) -> "Origin":
101 return Origin(self)102

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

lines 103–110why, one step back
103 def copy_with(self, **kwargs: typing.Any) -> "URL":
104 return URL(self.components.copy_with(**kwargs))105106 def resolve_with(self, base_url: URLTypes) -> "URL":107 if isinstance(base_url, URL):108 base_url = base_url.components109 return URL(self.components.resolve_with(base_url))110

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 111–117why, one step back
111 def __hash__(self) -> int:
112 return hash(str(self))113114 def __eq__(self, other: typing.Any) -> bool:115 return isinstance(other, URL) and str(self) == str(other)116117 def __str__(self) -> str:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 119–126why, one step back
119
120 def __repr__(self) -> str:121 class_name = self.__class__.__name__122 url_str = str(self)123 return f"{class_name}({url_str!r})"124125126class Origin:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 132–137why, one step back
132 self.port = url.port
133134 def __eq__(self, other: typing.Any) -> bool:135 return (136 isinstance(other, self.__class__)137 and self.is_ssl == other.is_ssl

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 139–142why, one step back
139 and self.port == other.port
140 )141142 def __hash__(self) -> int:

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 144–150why, one step back
144
145146class Headers(typing.MutableMapping[str, str]):147 """148 A case-insensitive multidict.149 """150

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 152–157why, one step back
152 if headers is None:
153 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]154 elif isinstance(headers, Headers):155 self._list = list(headers.raw)156 elif isinstance(headers, dict):157 self._list = [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 159–162why, one step back
159 for k, v in headers.items()
160 ]161 else:162 self._list = [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 165why, one step back
165 ]

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 167–168why, one step back
167
168 @property

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 169–197why, one step back
169 def encoding(self) -> str:
170 """171 Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be172 seen in the wild.173 """174 if self._encoding is None:175 for encoding in ["ascii", "utf-8"]:176 for key, value in self.raw:177 try:178 key.decode(encoding)179 value.decode(encoding)180 except UnicodeDecodeError:181 break182 else:183 # The else block runs if 'break' did not occur, meaning184 # all values fitted the encoding.185 self._encoding = encoding186 break187 else:188 # The ISO-8859-1 encoding covers all 256 code points in a byte,189 # so will never raise decode errors.190 self._encoding = "iso-8859-1"191 return self._encoding192193 @encoding.setter194 def encoding(self, value: str) -> None:195 self._encoding = value196197 @property

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 199–202why, one step back
199 """
200 Returns a list of the raw header items, as byte pairs.201 May be mutated in-place.202 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 210–212why, one step back
210
211 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore212 return [

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 214–222why, one step back
214 for key, value in self._list
215 ]216217 def get(self, key: str, default: typing.Any = None) -> typing.Any:218 try:219 return self[key]220 except KeyError:221 return default222

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 224–230why, one step back
224 """
225 Return multiple header values.226 """227 get_header_key = key.lower().encode(self.encoding)228229 values = [230 item_value.decode(self.encoding)

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 231–234why, one step back
231 for item_key, item_value in self._list
232 if item_key == get_header_key233 ]234

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 235–242why, one step back
235 if not split_commas:
236 return values237238 split_values = []239 for value in values:240 split_values.extend([item.strip() for item in value.split(",")])241 return split_values242

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 244–252why, one step back
244 """
245 Return a single header value.246247 If there are multiple headers with the same key, then we concatenate248 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2249 """250 normalized_key = key.lower().encode(self.encoding)251252 items = []

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 254–259why, one step back
254 if header_key == normalized_key:
255 items.append(header_value.decode(self.encoding))256257 if items:258 return ", ".join(items)259

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 260–266why, one step back
260 raise KeyError(key)
261262 def __setitem__(self, key: str, value: str) -> None:263 """264 Set the header `key` to `value`, removing any duplicate entries.265 Retains insertion order.266 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 269–287why, one step back
269
270 found_indexes = []271 for idx, (item_key, item_value) in enumerate(self._list):272 if item_key == set_key:273 found_indexes.append(idx)274275 for idx in reversed(found_indexes[1:]):276 del self._list[idx]277278 if found_indexes:279 idx = found_indexes[0]280 self._list[idx] = (set_key, set_value)281 else:282 self._list.append((set_key, set_value))283284 def __delitem__(self, key: str) -> None:285 """286 Remove the header `key`.287 """

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 289–298why, one step back
289
290 pop_indexes = []291 for idx, (item_key, item_value) in enumerate(self._list):292 if item_key == del_key:293 pop_indexes.append(idx)294295 for idx in reversed(pop_indexes):296 del self._list[idx]297298 def __contains__(self, key: typing.Any) -> bool:

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 300–317why, one step back
300 for header_key, header_value in self._list:
301 if header_key == get_header_key:302 return True303 return False304305 def __iter__(self) -> typing.Iterator[typing.Any]:306 return iter(self.keys())307308 def __len__(self) -> int:309 return len(self._list)310311 def __eq__(self, other: typing.Any) -> bool:312 if not isinstance(other, Headers):313 return False314 return sorted(self._list) == sorted(other._list)315316 def __repr__(self) -> str:317 class_name = self.__class__.__name__

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 318–322why, one step back
318
319 encoding_str = ""320 if self.encoding != "ascii":321 encoding_str = f", encoding={self.encoding!r}"322

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 328–336why, one step back
328
329330class Request:331 def __init__(332 self,333 method: str,334 url: typing.Union[str, URL],335 *,336 headers: HeaderTypes = None,

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 338–340why, one step back
338 ):
339 self.method = method.upper()340 self.url = URL(url) if isinstance(url, str) else url

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 344–345why, one step back
344 else:
345 self.is_streaming = True

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 347–352why, one step back
347 self.headers = Headers(headers)
348349 async def read(self) -> bytes:350 """351 Read and return the response content.352 """

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 356–358why, one step back
356 content += part
357 self.content = content358 return self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 363why, one step back
363 yield part

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

lines 364–365why, one step back
364 elif self.content:
365 yield self.content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 368–374why, one step back
368 """
369 Adds in any default headers. When using the `Client`, this will370 end up being called into by the `prepare_request()` stage.371372 You can omit this behavior by calling `Client.send()` with an373 explicitly built `Request` instance.374 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 375–382why, one step back
375 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]
376377 has_host = "host" in self.headers378 has_content_length = (379 "content-length" in self.headers or "transfer-encoding" in self.headers380 )381 has_accept_encoding = "accept-encoding" in self.headers382

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 390–402why, one step back
390 auto_headers.append((b"content-length", content_length))
391 if not has_accept_encoding:392 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))393394 for item in reversed(auto_headers):395 self.headers.raw.insert(0, item)396397398class Response:399 def __init__(400 self,401 status_code: int,402 *,

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 403–405why, one step back
403 reason_phrase: str = None,
404 protocol: str = None,405 headers: HeaderTypes = None,

Prefer 'content' over 'body'Tom Christiebefore adoption4255d41

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 407–411why, one step back
407 on_close: typing.Callable = None,
408 request: Request = None,409 history: typing.List["Response"] = None,410 ):411 self.status_code = status_code

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 413–415why, one step back
413 self.protocol = protocol
414 self.headers = Headers(headers)415

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 418–419why, one step back
418 self.is_stream_consumed = True
419 self._raw_content = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 420why, one step back
420 else:

Response.contentTom Christiebefore adoption4c55113

lines 421–423why, one step back
421 self.is_closed = False
422 self.is_stream_consumed = False423 self._raw_stream = content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 424why, one step back
424

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

response.next()Tom Christiebefore adoptiond652479

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 429–431why, one step back
429
430 @property431 def url(self) -> typing.Optional[URL]:

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 432–436why, one step back
432 """
433 Returns the URL for which the request was made.434435 Requires that `request` was provided when instantiating the response.436 """

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 438–439why, one step back
438
439 @property

Response.contentTom Christiebefore adoption4c55113

lines 440–442why, one step back
440 def content(self) -> bytes:
441 if not hasattr(self, "_content"):442 if hasattr(self, "_raw_content"):

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 443–445why, one step back
443 content = self.decoder.decode(self._raw_content)
444 content += self.decoder.flush()445 self._content = content

Response.contentTom Christiebefore adoption4c55113

lines 446–448why, one step back
446 else:
447 raise ResponseNotRead()448 return self._content

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

lines 449–493why, one step back
449
450 @property451 def text(self) -> str:452 if not hasattr(self, "_text"):453 content = self.content454 if not content:455 self._text = ""456 else:457 encoding = self.encoding458 self._text = content.decode(encoding, errors="replace")459 return self._text460461 @property462 def encoding(self) -> str:463 if not hasattr(self, "_encoding"):464 encoding = self.charset_encoding465 if encoding is None or not is_known_encoding(encoding):466 encoding = self.apparent_encoding467 if encoding is None or not is_known_encoding(encoding):468 encoding = "utf-8"469 self._encoding = encoding470 return self._encoding471472 @encoding.setter473 def encoding(self, value: str) -> None:474 self._encoding = value475476 @property477 def charset_encoding(self) -> typing.Optional[str]:478 """479 Return the encoding, as specified by the Content-Type header.480 """481 content_type = self.headers.get("Content-Type")482 if content_type is None:483 return None484485 parsed = cgi.parse_header(content_type)[-1]486 return parsed.get("charset")487488 @property489 def apparent_encoding(self) -> typing.Optional[str]:490 """491 Return the encoding, as it appears to autodetection.492 """493 return chardet.detect(self.content)["encoding"]

Response.contentTom Christiebefore adoption4c55113

lines 494–495why, one step back
494
495 @property

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 496–502why, one step back
496 def decoder(self) -> Decoder:
497 """498 Returns a decoder instance which can be used to decode the raw byte499 content, depending on the Content-Encoding used in the response.500 """501 if not hasattr(self, "_decoder"):502 decoders = [] # type: typing.List[Decoder]

Response.contentTom Christiebefore adoption4c55113

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

Rejig test and tighten up models APITom Christiebefore adoptiondea4d42

lines 504–506why, one step back
504 for value in values:
505 value = value.strip().lower()506 decoder_cls = SUPPORTED_DECODERS[value]

Clean up response interfaceTom Christiebefore adoption4d908d0

lines 507–516why, one step back
507 decoders.append(decoder_cls())
508509 if len(decoders) == 1:510 self._decoder = decoders[0]511 elif len(decoders) > 1:512 self._decoder = MultiDecoder(decoders)513 else:514 self._decoder = IdentityDecoder()515516 return self._decoder

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 517–521why, one step back
517
518 async def read(self) -> bytes:519 """520 Read and return the response content.521 """

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

Response.contentTom Christiebefore adoption4c55113

lines 525–527why, one step back
525 content += part
526 self._content = content527 return self._content

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 528–533why, one step back
528
529 async def stream(self) -> typing.AsyncIterator[bytes]:530 """531 A byte-iterator over the decoded response content.532 This allows us to handle gzip, deflate, and brotli encoded responses.533 """

Response.contentTom Christiebefore adoption4c55113

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 536–544why, one step back
536 else:
537 async for chunk in self.raw():538 yield self.decoder.decode(chunk)539 yield self.decoder.flush()540541 async def raw(self) -> typing.AsyncIterator[bytes]:542 """543 A byte-iterator over the raw response content.544 """

Response.contentTom Christiebefore adoption4c55113

lines 545–556why, one step back
545 if hasattr(self, "_raw_content"):
546 yield self._raw_content547 else:548 if self.is_stream_consumed:549 raise StreamConsumed()550 if self.is_closed:551 raise ResponseClosed()552553 self.is_stream_consumed = True554 async for part in self._raw_stream:555 yield part556 await self.close()

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 557–570why, one step back
557
558 async def close(self) -> None:559 """560 Close the response and release the connection.561 Automatically called if the response body is read to completion.562 """563 if not self.is_closed:564 self.is_closed = True565 if self.on_close is not None:566 await self.on_close()567568 @property569 def is_redirect(self) -> bool:570 return (

Finessing interfaceTom Christiebefore adoptiond7619a9

lines 571–579why, one step back
571 self.status_code
572 in (573 codes.moved_permanently,574 codes.found,575 codes.see_other,576 codes.temporary_redirect,577 codes.permanent_redirect,578 )579 and "location" in self.headers

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 580why, one step back
580 )