models.py
This file
Path
httpcore/models.py
839 lines · 25.7 KiB · Python
Last changed by
Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
History of this fileTake it
Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 1why, one step back1import asyncioAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
line 2why, one step back2import cgiMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 3why, one step back3import typingMerge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 4why, one step back4from urllib.parse import parse_qsl, urlencodeMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 5why, one step back5Add response.text and response.encodingTom Christiebefore adoptiond8df61b
line 6why, one step back6import chardetUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 7why, one step back7import rfc3986Add response.text and response.encodingTom Christiebefore adoptiond8df61b
line 8why, one step back8Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 9–15why, one step back9from .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 back16from .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 back23from .status_codes import codesAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 24–29why, one step back24from .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 back30Finessing interfaceTom Christiebefore adoptiond7619a9
line 31why, one step back31URLTypes = typing.Union["URL", str]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 32why, one step back32Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 33–39why, one step back33QueryParamTypes = typing.Union[34 "QueryParams",35 typing.Mapping[str, str],36 typing.List[typing.Tuple[typing.Any, typing.Any]],37 str,38]39Finessing interfaceTom Christiebefore adoptiond7619a9
lines 40–45why, one step back40HeaderTypes = typing.Union[41 "Headers",42 typing.Dict[typing.AnyStr, typing.AnyStr],43 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],44]45Auth (#65)Tom Christiebefore adoption5afa7dd
lines 46–47why, one step back46AuthTypes = typing.Union[47 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 48why, one step back48 typing.Callable[["Request"], "Request"],Auth (#65)Tom Christiebefore adoption5afa7dd
lines 49–50why, one step back49]50Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 51why, one step back51RequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]Finessing interfaceTom Christiebefore adoptiond7619a9
line 52why, one step back52Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 53why, one step back53ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]Finessing interfaceTom Christiebefore adoptiond7619a9
line 54why, one step back54Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 55why, one step back55Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 56why, one step back56class URL:Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 57–62why, one step back57 def __init__(58 self,59 url: URLTypes,60 allow_relative: bool = False,61 query_params: QueryParamTypes = None,62 ) -> None:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 63why, one step back63 if isinstance(url, rfc3986.uri.URIReference):Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 64why, one step back64 self.components = urlAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 65–66why, one step back65 elif isinstance(url, str):66 self.components = rfc3986.api.uri_reference(url)Finessing interfaceTom Christiebefore adoptiond7619a9
lines 67–69why, one step back67 else:68 self.components = url.components69Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 70–75why, one step back70 # Handle IDNA domain names.71 if self.components.authority:72 idna_authority = self.components.authority.encode("idna").decode("ascii")73 if idna_authority != self.components.authority:74 self.components = self.components.copy_with(authority=idna_authority)75Fix docstringsTom Christiebefore adoption8a227c1
line 76why, one step back76 # Normalize scheme and domain name.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 77–78why, one step back77 self.components = self.components.normalize()78Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 79–83why, one step back79 # Add any query parameters.80 if query_params:81 query_string = str(QueryParams(query_params))82 self.components = self.components.copy_with(query=query_string)83Add idna support. More tests.Tom Christiebefore adoptionb948798
line 84why, one step back84 # Enforce absolute URLs by default.Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 85–90why, one step back85 if not allow_relative:86 if not self.scheme:87 raise InvalidURL("No scheme included in URL.")88 if self.scheme not in ("http", "https"):89 raise InvalidURL('URL scheme must be "http" or "https".')90 if not self.host:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 91why, one step back91 raise InvalidURL("No host included in URL.")Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 92–94why, one step back9293 @property94 def scheme(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 95why, one step back95 return self.components.scheme or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 96–97why, one step back9697 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 98–99why, one step back98 def authority(self) -> str:99 return self.components.authority or ""Auth (#65)Tom Christiebefore adoption5afa7dd
lines 100–103why, one step back100101 @property102 def username(self) -> str:103 userinfo = self.components.userinfo or ""Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 104why, one step back104 return userinfo.partition(":")[0]Auth (#65)Tom Christiebefore adoption5afa7dd
lines 105–108why, one step back105106 @property107 def password(self) -> str:108 userinfo = self.components.userinfo or ""Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 109why, one step back109 return userinfo.partition(":")[2]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 110–111why, one step back110111 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 112–113why, one step back112 def host(self) -> str:113 return self.components.host or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 114–119why, one step back114115 @property116 def port(self) -> int:117 port = self.components.port118 if port is None:119 return {"https": 443, "http": 80}[self.scheme]Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 120why, one step back120 return int(port)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 121–122why, one step back121122 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 123–130why, one step back123 def path(self) -> str:124 return self.components.path or "/"125126 @property127 def query(self) -> str:128 return self.components.query or ""129130 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 131why, one step back131 def full_path(self) -> str:Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
lines 132–134why, one step back132 path = self.path133 if self.query:134 path += "?" + self.queryMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 135–137why, one step back135 return path136137 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 138–141why, one step back138 def fragment(self) -> str:139 return self.components.fragment or ""140141 @propertyCarefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 142why, one step back142 def is_ssl(self) -> bool:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 143–145why, one step back143 return self.components.scheme == "https"144145 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 146–155why, one step back146 def is_absolute_url(self) -> bool:147 """148 Return `True` for absolute URLs such as 'http://example.com/path',149 and `False` for relative URLs such as '/path'.150 """151 # We don't use rfc3986's `is_absolute` because it treats152 # URLs with a fragment portion as not absolute.153 # What we actually care about is if the URL provides154 # a scheme and hostname to which connections should be made.155 return self.components.scheme and self.components.hostUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 156–157why, one step back156157 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 158–161why, one step back158 def is_relative_url(self) -> bool:159 return not self.is_absolute_url160161 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 162–164why, one step back162 def origin(self) -> "Origin":163 return Origin(self)164Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 165–168why, one step back165 def copy_with(self, **kwargs: typing.Any) -> "URL":166 return URL(self.components.copy_with(**kwargs))167168 def resolve_with(self, base_url: URLTypes) -> "URL":Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 169–172why, one step back169 """170 Return an absolute URL, using base_url as the base.171 """172 # We drop any fragment portion, because RFC 3986 strictlyFix docstringsTom Christiebefore adoption8a227c1
line 173why, one step back173 # treats URLs with a fragment portion as not being absolute URLs.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 174–175why, one step back174 base_url = URL(base_url).copy_with(fragment=None)175 return URL(self.components.resolve_with(base_url.components))Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 176why, one step back176Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 177–183why, one step back177 def __hash__(self) -> int:178 return hash(str(self))179180 def __eq__(self, other: typing.Any) -> bool:181 return isinstance(other, URL) and str(self) == str(other)182183 def __str__(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 184why, one step back184 return self.components.unsplit()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 185–192why, one step back185186 def __repr__(self) -> str:187 class_name = self.__class__.__name__188 url_str = str(self)189 return f"{class_name}({url_str!r})"190191192class Origin:Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 193–196why, one step back193 """194 The URL scheme and authority information, as a comparable, hashable object.195 """196Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 197–198why, one step back197 def __init__(self, url: URLTypes) -> None:198 if not isinstance(url, URL):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 199why, one step back199 url = URL(url)Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 200why, one step back200 self.is_ssl = url.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 201why, one step back201 self.host = url.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 202–207why, one step back202 self.port = url.port203204 def __eq__(self, other: typing.Any) -> bool:205 return (206 isinstance(other, self.__class__)207 and self.is_ssl == other.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 208why, one step back208 and self.host == other.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 209–212why, one step back209 and self.port == other.port210 )211212 def __hash__(self) -> int:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 213why, one step back213 return hash((self.is_ssl, self.host, self.port))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 214–215why, one step back214215Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 216why, one step back216class QueryParams(typing.Mapping[str, str]):Improve class __repr__Tom Christiebefore adoption666d5a8
lines 217–220why, one step back217 """218 URL query parameters, as a multi-dict.219 """220Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 221–284why, one step back221 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:222 assert len(args) < 2, "Too many arguments."223 assert not (args and kwargs), "Cannot mix named and unnamed arguments."224225 value = args[0] if args else kwargs226227 if isinstance(value, str):228 items = parse_qsl(value)229 elif isinstance(value, QueryParams):230 items = value.multi_items()231 elif isinstance(value, list):232 items = value233 else:234 items = value.items() # type: ignore235236 self._list = [(str(k), str(v)) for k, v in items]237 self._dict = {str(k): str(v) for k, v in items}238239 def getlist(self, key: typing.Any) -> typing.List[str]:240 return [item_value for item_key, item_value in self._list if item_key == key]241242 def keys(self) -> typing.KeysView:243 return self._dict.keys()244245 def values(self) -> typing.ValuesView:246 return self._dict.values()247248 def items(self) -> typing.ItemsView:249 return self._dict.items()250251 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:252 return list(self._list)253254 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:255 if key in self._dict:256 return self._dict[key]257 return default258259 def __getitem__(self, key: typing.Any) -> str:260 return self._dict[key]261262 def __contains__(self, key: typing.Any) -> bool:263 return key in self._dict264265 def __iter__(self) -> typing.Iterator[typing.Any]:266 return iter(self.keys())267268 def __len__(self) -> int:269 return len(self._dict)270271 def __eq__(self, other: typing.Any) -> bool:272 if not isinstance(other, self.__class__):273 return False274 return sorted(self._list) == sorted(other._list)275276 def __str__(self) -> str:277 return urlencode(self._list)278279 def __repr__(self) -> str:280 class_name = self.__class__.__name__281 query_string = str(self)282 return f"{class_name}({query_string!r})"283284Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 285–286why, one step back285class Headers(typing.MutableMapping[str, str]):286 """Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 287why, one step back287 HTTP headers, as a case-insensitive multi-dict.Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 288–289why, one step back288 """289Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 290why, one step back290 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 291–296why, one step back291 if headers is None:292 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]293 elif isinstance(headers, Headers):294 self._list = list(headers.raw)295 elif isinstance(headers, dict):296 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 297why, one step back297 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 298–301why, one step back298 for k, v in headers.items()299 ]300 else:301 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 302–303why, one step back302 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))303 for k, v in headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 304why, one step back304 ]Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 305why, one step back305 self._encoding = encodingMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 306–307why, one step back306307 @propertyRejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 308–309why, one step back308 def encoding(self) -> str:309 """Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 310–311why, one step back310 Header encoding is mandated as ascii, but we allow fallbacks to utf-8311 or iso-8859-1.Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 312–336why, one step back312 """313 if self._encoding is None:314 for encoding in ["ascii", "utf-8"]:315 for key, value in self.raw:316 try:317 key.decode(encoding)318 value.decode(encoding)319 except UnicodeDecodeError:320 break321 else:322 # The else block runs if 'break' did not occur, meaning323 # all values fitted the encoding.324 self._encoding = encoding325 break326 else:327 # The ISO-8859-1 encoding covers all 256 code points in a byte,328 # so will never raise decode errors.329 self._encoding = "iso-8859-1"330 return self._encoding331332 @encoding.setter333 def encoding(self, value: str) -> None:334 self._encoding = value335336 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 337why, one step back337 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 338–341why, one step back338 """339 Returns a list of the raw header items, as byte pairs.340 May be mutated in-place.341 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 342–344why, one step back342 return self._list343344 def keys(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 345why, one step back345 return [key.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 346–347why, one step back346347 def values(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 348why, one step back348 return [value.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 349–351why, one step back349350 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore351 return [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 352why, one step back352 (key.decode(self.encoding), value.decode(self.encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 353–361why, one step back353 for key, value in self._list354 ]355356 def get(self, key: str, default: typing.Any = None) -> typing.Any:357 try:358 return self[key]359 except KeyError:360 return default361Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 362why, one step back362 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 363–369why, one step back363 """364 Return multiple header values.365 """366 get_header_key = key.lower().encode(self.encoding)367368 values = [369 item_value.decode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 370–373why, one step back370 for item_key, item_value in self._list371 if item_key == get_header_key372 ]373Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 374–381why, one step back374 if not split_commas:375 return values376377 split_values = []378 for value in values:379 split_values.extend([item.strip() for item in value.split(",")])380 return split_values381Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 382why, one step back382 def __getitem__(self, key: str) -> str:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 383–391why, one step back383 """384 Return a single header value.385386 If there are multiple headers with the same key, then we concatenate387 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2388 """389 normalized_key = key.lower().encode(self.encoding)390391 items = []Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 392why, one step back392 for header_key, header_value in self._list:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 393–398why, one step back393 if header_key == normalized_key:394 items.append(header_value.decode(self.encoding))395396 if items:397 return ", ".join(items)398Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 399–405why, one step back399 raise KeyError(key)400401 def __setitem__(self, key: str, value: str) -> None:402 """403 Set the header `key` to `value`, removing any duplicate entries.404 Retains insertion order.405 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 406–407why, one step back406 set_key = key.lower().encode(self.encoding)407 set_value = value.encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 408–426why, one step back408409 found_indexes = []410 for idx, (item_key, item_value) in enumerate(self._list):411 if item_key == set_key:412 found_indexes.append(idx)413414 for idx in reversed(found_indexes[1:]):415 del self._list[idx]416417 if found_indexes:418 idx = found_indexes[0]419 self._list[idx] = (set_key, set_value)420 else:421 self._list.append((set_key, set_value))422423 def __delitem__(self, key: str) -> None:424 """425 Remove the header `key`.426 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 427why, one step back427 del_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 428–437why, one step back428429 pop_indexes = []430 for idx, (item_key, item_value) in enumerate(self._list):431 if item_key == del_key:432 pop_indexes.append(idx)433434 for idx in reversed(pop_indexes):435 del self._list[idx]436437 def __contains__(self, key: typing.Any) -> bool:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 438why, one step back438 get_header_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 439–456why, one step back439 for header_key, header_value in self._list:440 if header_key == get_header_key:441 return True442 return False443444 def __iter__(self) -> typing.Iterator[typing.Any]:445 return iter(self.keys())446447 def __len__(self) -> int:448 return len(self._list)449450 def __eq__(self, other: typing.Any) -> bool:451 if not isinstance(other, Headers):452 return False453 return sorted(self._list) == sorted(other._list)454455 def __repr__(self) -> str:456 class_name = self.__class__.__name__Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 457–461why, one step back457458 encoding_str = ""459 if self.encoding != "ascii":460 encoding_str = f", encoding={self.encoding!r}"461Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 462–463why, one step back462 as_dict = dict(self.items())463 if len(as_dict) == len(self):Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 464–466why, one step back464 return f"{class_name}({as_dict!r}{encoding_str})"465 as_list = self.items()466 return f"{class_name}({as_list!r}{encoding_str})"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 467–474why, one step back467468469class Request:470 def __init__(471 self,472 method: str,473 url: typing.Union[str, URL],474 *,Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 475why, one step back475 data: RequestData = b"",Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 476why, one step back476 query_params: QueryParamTypes = None,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 477–479why, one step back477 headers: HeaderTypes = None,478 ):479 self.method = method.upper()Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 480why, one step back480 self.url = URL(url, query_params=query_params)Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
lines 481–483why, one step back481 self.headers = Headers(headers)482483 if isinstance(data, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 484why, one step back484 self.is_streaming = FalseMerge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
lines 485–489why, one step back485 self.content = data486 elif isinstance(data, dict):487 self.is_streaming = False488 self.content = urlencode(data, doseq=True).encode("utf-8")489 self.headers["Content-Type"] = "application/x-www-form-urlencoded"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 490–491why, one step back490 else:491 self.is_streaming = TrueMerge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 492why, one step back492 self.content_aiter = dataMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 493–497why, one step back493494 async def read(self) -> bytes:495 """496 Read and return the response content.497 """Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 498why, one step back498 if not hasattr(self, "content"):Merge pull request #53 from yunstanford/patch-0Tom Christiebefore adoption21ac95a
line 499why, one step back499 self.content = b"".join([part async for part in self.stream()])Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 500why, one step back500 return self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 501–503why, one step back501502 async def stream(self) -> typing.AsyncIterator[bytes]:503 if self.is_streaming:Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 504why, one step back504 async for part in self.content_aiter:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 505why, one step back505 yield partPrefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 506–507why, one step back506 elif self.content:507 yield self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 508–509why, one step back508509 def prepare(self) -> None:Response.contentTom Christiebefore adoption4c55113
lines 510–516why, one step back510 """511 Adds in any default headers. When using the `Client`, this will512 end up being called into by the `prepare_request()` stage.513514 You can omit this behavior by calling `Client.send()` with an515 explicitly built `Request` instance.516 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 517–524why, one step back517 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]518519 has_host = "host" in self.headers520 has_content_length = (521 "content-length" in self.headers or "transfer-encoding" in self.headers522 )523 has_accept_encoding = "accept-encoding" in self.headers524Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 525–526why, one step back525 if not has_host and self.url.authority:526 auto_headers.append((b"host", self.url.authority.encode("ascii")))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 527–529why, one step back527 if not has_content_length:528 if self.is_streaming:529 auto_headers.append((b"transfer-encoding", b"chunked"))Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 530–531why, one step back530 elif self.content:531 content_length = str(len(self.content)).encode()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 532–538why, one step back532 auto_headers.append((b"content-length", content_length))533 if not has_accept_encoding:534 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))535536 for item in reversed(auto_headers):537 self.headers.raw.insert(0, item)538Still truckin' onTom Christiebefore adoption6cb5c0d
lines 539–541why, one step back539 def __repr__(self) -> str:540 class_name = self.__class__.__name__541 url = str(self.url)Improve class __repr__Tom Christiebefore adoption666d5a8
line 542why, one step back542 return f"<{class_name}({self.method!r}, {url!r})>"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 543why, one step back543Still truckin' onTom Christiebefore adoption6cb5c0d
line 544why, one step back544Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 545–549why, one step back545class Response:546 def __init__(547 self,548 status_code: int,549 *,Finessing interfaceTom Christiebefore adoptiond7619a9
lines 550–552why, one step back550 reason_phrase: str = None,551 protocol: str = None,552 headers: HeaderTypes = None,Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 553why, one step back553 content: ResponseContent = b"",Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 554–557why, one step back554 on_close: typing.Callable = None,555 request: Request = None,556 history: typing.List["Response"] = None,557 ):Truckin' onTom Christiebefore adoption6b60d95
lines 558–559why, one step back558 try:559 # Use a StatusCode IntEnum if possible, for a nicer representation.Still truckin' onTom Christiebefore adoption6cb5c0d
line 560why, one step back560 self.status_code = codes(status_code) # type: intTruckin' onTom Christiebefore adoption6b60d95
lines 561–562why, one step back561 except ValueError:562 self.status_code = status_codeResponse.contentTom Christiebefore adoption4c55113
line 563why, one step back563 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 564–566why, one step back564 self.protocol = protocol565 self.headers = Headers(headers)566Response.contentTom Christiebefore adoption4c55113
line 567why, one step back567 if isinstance(content, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 568why, one step back568 self.is_closed = TrueResponse.contentTom Christiebefore adoption4c55113
lines 569–570why, one step back569 self.is_stream_consumed = True570 self._raw_content = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 571why, one step back571 else:Response.contentTom Christiebefore adoption4c55113
lines 572–574why, one step back572 self.is_closed = False573 self.is_stream_consumed = False574 self._raw_stream = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 575why, one step back575Response.contentTom Christiebefore adoption4c55113
line 576why, one step back576 self.on_close = on_closeMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 577–578why, one step back577 self.request = request578 self.history = [] if history is None else list(history)response.next()Tom Christiebefore adoptiond652479
line 579why, one step back579 self.next = None # typing.Optional[typing.Callable]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 580–582why, one step back580581 @property582 def url(self) -> typing.Optional[URL]:Clean up response interfaceTom Christiebefore adoption4d908d0
lines 583–587why, one step back583 """584 Returns the URL for which the request was made.585586 Requires that `request` was provided when instantiating the response.587 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 588why, one step back588 return None if self.request is None else self.request.urlClean up response interfaceTom Christiebefore adoption4d908d0
lines 589–590why, one step back589590 @propertyResponse.contentTom Christiebefore adoption4c55113
lines 591–593why, one step back591 def content(self) -> bytes:592 if not hasattr(self, "_content"):593 if hasattr(self, "_raw_content"):Add response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 594–596why, one step back594 content = self.decoder.decode(self._raw_content)595 content += self.decoder.flush()596 self._content = contentResponse.contentTom Christiebefore adoption4c55113
lines 597–599why, one step back597 else:598 raise ResponseNotRead()599 return self._contentAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 600–635why, one step back600601 @property602 def text(self) -> str:603 if not hasattr(self, "_text"):604 content = self.content605 if not content:606 self._text = ""607 else:608 encoding = self.encoding609 self._text = content.decode(encoding, errors="replace")610 return self._text611612 @property613 def encoding(self) -> str:614 if not hasattr(self, "_encoding"):615 encoding = self.charset_encoding616 if encoding is None or not is_known_encoding(encoding):617 encoding = self.apparent_encoding618 if encoding is None or not is_known_encoding(encoding):619 encoding = "utf-8"620 self._encoding = encoding621 return self._encoding622623 @encoding.setter624 def encoding(self, value: str) -> None:625 self._encoding = value626627 @property628 def charset_encoding(self) -> typing.Optional[str]:629 """630 Return the encoding, as specified by the Content-Type header.631 """632 content_type = self.headers.get("Content-Type")633 if content_type is None:634 return None635Truckin' onTom Christiebefore adoption0ca1c84
lines 636–640why, one step back636 parsed = cgi.parse_header(content_type)637 media_type, params = parsed[0], parsed[-1]638 if "charset" in params:639 return params["charset"].strip("'\"")640Media types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 641–643why, one step back641 # RFC 2616 specifies that 'iso-8859-1' should be used as the default642 # for 'text/*' media types, if no charset is provided.643 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1Truckin' onTom Christiebefore adoption0ca1c84
lines 644–647why, one step back644 if media_type.startswith("text/"):645 return "iso-8859-1"646647 return NoneAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 648–654why, one step back648649 @property650 def apparent_encoding(self) -> typing.Optional[str]:651 """652 Return the encoding, as it appears to autodetection.653 """654 return chardet.detect(self.content)["encoding"]Response.contentTom Christiebefore adoption4c55113
lines 655–656why, one step back655656 @propertyClean up response interfaceTom Christiebefore adoption4d908d0
lines 657–663why, one step back657 def decoder(self) -> Decoder:658 """659 Returns a decoder instance which can be used to decode the raw byte660 content, depending on the Content-Encoding used in the response.661 """662 if not hasattr(self, "_decoder"):663 decoders = [] # type: typing.List[Decoder]Response.contentTom Christiebefore adoption4c55113
line 664why, one step back664 values = self.headers.getlist("content-encoding", split_commas=True)Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 665–667why, one step back665 for value in values:666 value = value.strip().lower()667 decoder_cls = SUPPORTED_DECODERS[value]Clean up response interfaceTom Christiebefore adoption4d908d0
lines 668–677why, one step back668 decoders.append(decoder_cls())669670 if len(decoders) == 1:671 self._decoder = decoders[0]672 elif len(decoders) > 1:673 self._decoder = MultiDecoder(decoders)674 else:675 self._decoder = IdentityDecoder()676677 return self._decoderMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 678–682why, one step back678679 async def read(self) -> bytes:680 """681 Read and return the response content.682 """Response.contentTom Christiebefore adoption4c55113
line 683why, one step back683 if not hasattr(self, "_content"):Merge pull request #53 from yunstanford/patch-0Tom Christiebefore adoption21ac95a
line 684why, one step back684 self._content = b"".join([part async for part in self.stream()])Response.contentTom Christiebefore adoption4c55113
line 685why, one step back685 return self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 686–691why, one step back686687 async def stream(self) -> typing.AsyncIterator[bytes]:688 """689 A byte-iterator over the decoded response content.690 This allows us to handle gzip, deflate, and brotli encoded responses.691 """Response.contentTom Christiebefore adoption4c55113
lines 692–693why, one step back692 if hasattr(self, "_content"):693 yield self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 694–702why, one step back694 else:695 async for chunk in self.raw():696 yield self.decoder.decode(chunk)697 yield self.decoder.flush()698699 async def raw(self) -> typing.AsyncIterator[bytes]:700 """701 A byte-iterator over the raw response content.702 """Response.contentTom Christiebefore adoption4c55113
lines 703–714why, one step back703 if hasattr(self, "_raw_content"):704 yield self._raw_content705 else:706 if self.is_stream_consumed:707 raise StreamConsumed()708 if self.is_closed:709 raise ResponseClosed()710711 self.is_stream_consumed = True712 async for part in self._raw_stream:713 yield part714 await self.close()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 715–728why, one step back715716 async def close(self) -> None:717 """718 Close the response and release the connection.719 Automatically called if the response body is read to completion.720 """721 if not self.is_closed:722 self.is_closed = True723 if self.on_close is not None:724 await self.on_close()725726 @property727 def is_redirect(self) -> bool:728 return (Finessing interfaceTom Christiebefore adoptiond7619a9
lines 729–730why, one step back729 self.status_code730 in (Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369
lines 731–735why, one step back731 codes.MOVED_PERMANENTLY,732 codes.FOUND,733 codes.SEE_OTHER,734 codes.TEMPORARY_REDIRECT,735 codes.PERMANENT_REDIRECT,Finessing interfaceTom Christiebefore adoptiond7619a9
lines 736–737why, one step back736 )737 and "location" in self.headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 738why, one step back738 )Still truckin' onTom Christiebefore adoption6cb5c0d
line 739why, one step back739Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 740–757why, one step back740 def raise_for_status(self) -> None:741 """742 Raise the `HttpError` if one occurred.743 """744 message = (745 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"746 "For more information check: https://httpstatuses.com/{0.status_code}"747 )748749 if 400 <= self.status_code < 500:750 message = message.format(self, error_type="Client Error")751 elif 500 <= self.status_code < 600:752 message = message.format(self, error_type="Server Error")753 else:754 message = ""755756 if message:757 raise HttpError(message)Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 758–759why, one step back758759 def __repr__(self) -> str:repr change: <SyncResponse ...> -> <Response ...>Tom Christiebefore adoption73d5fca
line 760why, one step back760 return f"<Response({self.status_code}, {self.reason_phrase!r})>"Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 761–823why, one step back761762763class SyncResponse:764 """765 A thread-synchronous response. This class proxies onto a `Response`766 instance, providing standard synchronous interfaces where required.767 """768769 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):770 self._response = response771 self._loop = loop772773 @property774 def status_code(self) -> int:775 return self._response.status_code776777 @property778 def reason_phrase(self) -> str:779 return self._response.reason_phrase780781 @property782 def protocol(self) -> typing.Optional[str]:783 return self._response.protocol784785 @property786 def url(self) -> typing.Optional[URL]:787 return self._response.url788789 @property790 def request(self) -> typing.Optional[Request]:791 return self._response.request792793 @property794 def headers(self) -> Headers:795 return self._response.headers796797 @property798 def content(self) -> bytes:799 return self._response.content800801 @property802 def text(self) -> str:803 return self._response.text804805 @property806 def encoding(self) -> str:807 return self._response.encoding808809 @property810 def is_redirect(self) -> bool:811 return self._response.is_redirect812813 def raise_for_status(self) -> None:814 return self._response.raise_for_status()815816 def read(self) -> bytes:817 return self._loop.run_until_complete(self._response.read())818819 def stream(self) -> typing.Iterator[bytes]:820 inner = self._response.stream()821 while True:822 try:823 yield self._loop.run_until_complete(inner.__anext__())Include URL.__hash__ in test (#64)Yeray Diaz Diazbefore adoption2e9ab2e
line 824why, one step back824 except StopAsyncIteration:Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 825–831why, one step back825 break826827 def raw(self) -> typing.Iterator[bytes]:828 inner = self._response.raw()829 while True:830 try:831 yield self._loop.run_until_complete(inner.__anext__())Include URL.__hash__ in test (#64)Yeray Diaz Diazbefore adoption2e9ab2e
line 832why, one step back832 except StopAsyncIteration:Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 833–836why, one step back833 break834835 def close(self) -> None:836 return self._loop.run_until_complete(self._response.close())Merge pull request #56 from yeraydiazdiaz/test-additional-http-methodsTom Christiebefore adoption87cab4c
lines 837–838why, one step back837838 def __repr__(self) -> str:repr change: <SyncResponse ...> -> <Response ...>Tom Christiebefore adoption73d5fca
line 839why, one step back839 return f"<Response({self.status_code}, {self.reason_phrase!r})>"