Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/requests/models.py: 60%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

527 statements  

1""" 

2requests.models 

3~~~~~~~~~~~~~~~ 

4 

5This module contains the primary objects that power Requests. 

6""" 

7 

8from __future__ import annotations 

9 

10import datetime 

11 

12# Import encoding now, to avoid implicit import later. 

13# Implicit import within threads may cause LookupError when standard library is in a ZIP, 

14# such as in Embedded Python. See https://github.com/psf/requests/issues/3578. 

15import encodings.idna # noqa: F401 # type: ignore[reportUnusedImport] 

16from collections.abc import Callable, Generator, Iterable, Iterator, Mapping 

17from io import UnsupportedOperation 

18from typing import ( 

19 TYPE_CHECKING, 

20 Any, 

21 Final, 

22 Literal, 

23 cast, 

24 overload, 

25) 

26 

27from urllib3.exceptions import ( 

28 DecodeError, 

29 LocationParseError, 

30 ProtocolError, 

31 ReadTimeoutError, 

32 SSLError, 

33) 

34from urllib3.fields import RequestField 

35from urllib3.filepost import encode_multipart_formdata 

36from urllib3.util import parse_url 

37 

38from ._internal_utils import to_native_string, unicode_is_ascii 

39from ._types import SupportsRead as _SupportsRead 

40from .auth import HTTPBasicAuth 

41from .compat import ( 

42 JSONDecodeError, 

43 basestring, 

44 builtin_str, 

45 chardet, 

46 cookielib, 

47 urlencode, 

48 urlsplit, 

49 urlunparse, 

50) 

51from .compat import json as complexjson 

52from .cookies import ( 

53 _copy_cookie_jar, # type: ignore[reportPrivateUsage] 

54 cookiejar_from_dict, 

55 get_cookie_header, 

56) 

57from .exceptions import ( 

58 ChunkedEncodingError, 

59 ConnectionError, 

60 ContentDecodingError, 

61 HTTPError, 

62 InvalidJSONError, 

63 InvalidURL, 

64 MissingSchema, 

65 StreamConsumedError, 

66) 

67from .exceptions import JSONDecodeError as RequestsJSONDecodeError 

68from .exceptions import SSLError as RequestsSSLError 

69from .hooks import default_hooks 

70from .status_codes import codes 

71from .structures import CaseInsensitiveDict 

72from .utils import ( 

73 check_header_validity, 

74 get_auth_from_url, 

75 guess_filename, 

76 guess_json_utf, 

77 iter_slices, 

78 parse_header_links, 

79 requote_uri, 

80 stream_decode_response_unicode, 

81 super_len, 

82 to_key_val_list, 

83) 

84 

85if TYPE_CHECKING: 

86 from http.cookiejar import CookieJar 

87 

88 from typing_extensions import Self 

89 

90 from . import _types as _t 

91 from .adapters import HTTPAdapter 

92 from .cookies import RequestsCookieJar 

93 

94#: The set of HTTP status codes that indicate an automatically 

95#: processable redirect. 

96REDIRECT_STATI: Final[tuple[int, ...]] = ( # type: ignore[assignment] 

97 codes.moved, # 301 

98 codes.found, # 302 

99 codes.other, # 303 

100 codes.temporary_redirect, # 307 

101 codes.permanent_redirect, # 308 

102) 

103 

104DEFAULT_REDIRECT_LIMIT: int = 30 

105CONTENT_CHUNK_SIZE: int = 10 * 1024 

106ITER_CHUNK_SIZE: int = 512 

107 

108 

109class RequestEncodingMixin: 

110 url: str | None 

111 

112 @property 

113 def path_url(self) -> str: 

114 """Build the path URL to use.""" 

115 

116 url: list[str] = [] 

117 

118 p = urlsplit(cast(str, self.url)) 

119 

120 path = p.path 

121 if not path: 

122 path = "/" 

123 

124 url.append(path) 

125 

126 query = p.query 

127 if query: 

128 url.append("?") 

129 url.append(query) 

130 

131 return "".join(url) 

132 

133 @overload 

134 @staticmethod 

135 def _encode_params(data: str) -> str: ... 

136 

137 @overload 

138 @staticmethod 

139 def _encode_params(data: bytes) -> bytes: ... 

140 

141 @overload 

142 @staticmethod 

143 def _encode_params( 

144 data: _t.SupportsRead[str | bytes], 

145 ) -> _t.SupportsRead[str | bytes]: ... 

146 

147 @overload 

148 @staticmethod 

149 def _encode_params(data: _t.KVDataType) -> str: ... 

150 

151 @staticmethod 

152 def _encode_params( 

153 data: _t.EncodableDataType, 

154 ) -> str | bytes | _t.SupportsRead[str | bytes]: 

155 """Encode parameters in a piece of data. 

156 

157 Will successfully encode parameters when passed as a dict or a list of 

158 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary 

159 if parameters are supplied as a dict. 

160 """ 

161 

162 if isinstance(data, (str, bytes)): 

163 return data 

164 elif isinstance(data, _SupportsRead): 

165 return data 

166 elif hasattr(data, "__iter__"): 

167 result: list[tuple[bytes, bytes]] = [] 

168 for k, vs in to_key_val_list(data): 

169 if isinstance(vs, basestring) or not hasattr(vs, "__iter__"): 

170 vs = [vs] 

171 for v in vs: 

172 if v is not None: 

173 result.append( 

174 ( 

175 k.encode("utf-8") if isinstance(k, str) else k, 

176 v.encode("utf-8") if isinstance(v, str) else v, 

177 ) 

178 ) 

179 return urlencode(result, doseq=True) 

180 else: 

181 return data # type: ignore[return-value] # unreachable for valid _t.DataType 

182 

183 @staticmethod 

184 def _encode_files( 

185 files: _t.FilesType, data: _t.RawDataType | None 

186 ) -> tuple[bytes, str]: 

187 """Build the body for a multipart/form-data request. 

188 

189 Will successfully encode files when passed as a dict or a list of 

190 tuples. Order is retained if data is a list of tuples but arbitrary 

191 if parameters are supplied as a dict. 

192 The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) 

193 or 4-tuples (filename, fileobj, contentype, custom_headers). 

194 """ 

195 if not files: 

196 raise ValueError("Files must be provided.") 

197 elif isinstance(data, basestring): 

198 raise ValueError("Data must not be a string.") 

199 

200 new_fields: list[RequestField | tuple[str, bytes]] = [] 

201 fields = to_key_val_list(data or {}) 

202 files = to_key_val_list(files or {}) 

203 

204 for field, val in fields: 

205 if isinstance(val, basestring) or not hasattr(val, "__iter__"): 

206 val = [val] 

207 for v in val: 

208 if v is not None: 

209 # Don't call str() on bytestrings: in Py3 it all goes wrong. 

210 if not isinstance(v, bytes): 

211 v = str(v) 

212 

213 new_fields.append( 

214 ( 

215 field.decode("utf-8") 

216 if isinstance(field, bytes) 

217 else field, 

218 v.encode("utf-8") if isinstance(v, str) else v, 

219 ) 

220 ) 

221 

222 for k, v in files: 

223 # support for explicit filename 

224 ft = None 

225 fh = None 

226 if isinstance(v, (tuple, list)): 

227 if len(v) == 2: 

228 fn, fp = v 

229 elif len(v) == 3: 

230 fn, fp, ft = v 

231 else: 

232 fn, fp, ft, fh = v 

233 else: 

234 fn = guess_filename(v) or k 

235 fp = v 

236 

237 if isinstance(fp, (str, bytes, bytearray)): 

238 fdata = fp 

239 elif isinstance(fp, _SupportsRead): # type: ignore[reportUnnecessaryIsInstance] # defensive check for untyped callers 

240 fdata = fp.read() 

241 elif fp is None: # defensive check for untyped callers 

242 continue 

243 else: 

244 fdata = fp 

245 

246 rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) 

247 rf.make_multipart(content_type=ft) 

248 new_fields.append(rf) 

249 

250 body, content_type = encode_multipart_formdata(new_fields) 

251 

252 return body, content_type 

253 

254 

255class RequestHooksMixin: 

256 hooks: dict[str, list[_t.HookType]] 

257 

258 def register_hook( 

259 self, event: str, hook: Iterable[_t.HookType] | _t.HookType 

260 ) -> None: 

261 """Properly register a hook.""" 

262 

263 if event not in self.hooks: 

264 raise ValueError(f'Unsupported event specified, with event name "{event}"') 

265 

266 if isinstance(hook, Callable): 

267 self.hooks[event].append(hook) 

268 elif hasattr(hook, "__iter__"): 

269 self.hooks[event].extend(h for h in hook if isinstance(h, Callable)) # type: ignore[reportUnnecessaryIsInstance] # defensive runtime filter 

270 

271 def deregister_hook(self, event: str, hook: _t.HookType) -> bool: 

272 """Deregister a previously registered hook. 

273 Returns True if the hook existed, False if not. 

274 """ 

275 

276 try: 

277 self.hooks[event].remove(hook) 

278 return True 

279 except ValueError: 

280 return False 

281 

282 

283class Request(RequestHooksMixin): 

284 """A user-created :class:`Request <Request>` object. 

285 

286 Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server. 

287 

288 :param method: HTTP method to use. 

289 :param url: URL to send. 

290 :param headers: dictionary of headers to send. 

291 :param files: dictionary of {filename: fileobject} files to multipart upload. 

292 :param data: the body to attach to the request. If a dictionary or 

293 list of tuples ``[(key, value)]`` is provided, form-encoding will 

294 take place. 

295 :param json: json for the body to attach to the request (if files or data is not specified). 

296 :param params: URL parameters to append to the URL. If a dictionary or 

297 list of tuples ``[(key, value)]`` is provided, form-encoding will 

298 take place. 

299 :param auth: Auth handler or (user, pass) tuple. 

300 :param cookies: dictionary or CookieJar of cookies to attach to this request. 

301 :param hooks: dictionary of callback hooks, for internal usage. 

302 

303 Usage:: 

304 

305 >>> import requests 

306 >>> req = requests.Request('GET', 'https://httpbin.org/get') 

307 >>> req.prepare() 

308 <PreparedRequest [GET]> 

309 """ 

310 

311 hooks: dict[str, list[_t.HookType]] 

312 method: str | None 

313 url: _t.UriType | None 

314 headers: Mapping[str, str | bytes] 

315 files: _t.FilesType 

316 data: _t.DataType 

317 json: _t.JsonType 

318 params: _t.ParamsType 

319 auth: _t.AuthType 

320 cookies: RequestsCookieJar | CookieJar | dict[str, str] | None 

321 

322 def __init__( 

323 self, 

324 method: str | None = None, 

325 url: _t.UriType | None = None, 

326 headers: _t.HeadersType = None, 

327 files: _t.FilesType = None, 

328 data: _t.DataType = None, 

329 params: _t.ParamsType = None, 

330 auth: _t.AuthType = None, 

331 cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None, 

332 hooks: _t.HooksInputType | None = None, 

333 json: _t.JsonType = None, 

334 ) -> None: 

335 # Default empty dicts for dict params. 

336 data = [] if data is None else data 

337 files = [] if files is None else files 

338 headers = {} if headers is None else headers 

339 params = {} if params is None else params 

340 hooks = {} if hooks is None else hooks 

341 

342 self.hooks = default_hooks() 

343 for k, v in list(hooks.items()): 

344 self.register_hook(event=k, hook=v) 

345 

346 self.method = method 

347 self.url = url 

348 self.headers = headers 

349 self.files = files 

350 self.data = data 

351 self.json = json 

352 self.params = params 

353 self.auth = auth 

354 self.cookies = cookies 

355 

356 def __repr__(self) -> str: 

357 return f"<Request [{self.method}]>" 

358 

359 def prepare(self) -> PreparedRequest: 

360 """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.""" 

361 p = PreparedRequest() 

362 p.prepare( 

363 method=self.method, 

364 url=self.url, 

365 headers=self.headers, 

366 files=self.files, 

367 data=self.data, 

368 json=self.json, 

369 params=self.params, 

370 auth=self.auth, 

371 cookies=self.cookies, 

372 hooks=self.hooks, 

373 ) 

374 return p 

375 

376 

377class PreparedRequest(RequestEncodingMixin, RequestHooksMixin): 

378 """The fully mutable :class:`PreparedRequest <PreparedRequest>` object, 

379 containing the exact bytes that will be sent to the server. 

380 

381 Instances are generated from a :class:`Request <Request>` object, and 

382 should not be instantiated manually; doing so may produce undesirable 

383 effects. 

384 

385 Usage:: 

386 

387 >>> import requests 

388 >>> req = requests.Request('GET', 'https://httpbin.org/get') 

389 >>> r = req.prepare() 

390 >>> r 

391 <PreparedRequest [GET]> 

392 

393 >>> s = requests.Session() 

394 >>> s.send(r) 

395 <Response [200]> 

396 """ 

397 

398 method: str | None 

399 url: str | None 

400 headers: CaseInsensitiveDict[str | bytes] 

401 _cookies: RequestsCookieJar | CookieJar | None 

402 body: _t.BodyType 

403 hooks: dict[str, list[_t.HookType]] 

404 _body_position: int | object | None 

405 

406 def __init__(self) -> None: 

407 #: HTTP verb to send to the server. 

408 self.method = None 

409 #: HTTP URL to send the request to. 

410 self.url = None 

411 #: dictionary of HTTP headers. 

412 self.headers = None # type: ignore[assignment] 

413 # The `CookieJar` used to create the Cookie header will be stored here 

414 # after prepare_cookies is called 

415 self._cookies = None 

416 #: request body to send to the server. 

417 self.body = None 

418 #: dictionary of callback hooks, for internal usage. 

419 self.hooks = default_hooks() 

420 #: integer denoting starting position of a readable file-like body. 

421 self._body_position = None 

422 

423 def prepare( 

424 self, 

425 method: str | None = None, 

426 url: _t.UriType | None = None, 

427 headers: Mapping[str, str | bytes] | None = None, 

428 files: _t.FilesType = None, 

429 data: _t.DataType = None, 

430 params: _t.ParamsType = None, 

431 auth: _t.AuthType = None, 

432 cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None, 

433 hooks: _t.HooksInputType | None = None, 

434 json: _t.JsonType = None, 

435 ) -> None: 

436 """Prepares the entire request with the given parameters.""" 

437 

438 url = cast("_t.UriType", url) 

439 self.prepare_method(method) 

440 self.prepare_url(url, params) 

441 self.prepare_headers(headers) 

442 self.prepare_cookies(cookies) 

443 self.prepare_body(data, files, json) 

444 self.prepare_auth(auth, url) 

445 

446 # Note that prepare_auth must be last to enable authentication schemes 

447 # such as OAuth to work on a fully prepared request. 

448 

449 # This MUST go after prepare_auth. Authenticators could add a hook 

450 self.prepare_hooks(hooks) 

451 

452 def __repr__(self) -> str: 

453 return f"<PreparedRequest [{self.method}]>" 

454 

455 def copy(self) -> PreparedRequest: 

456 p = PreparedRequest() 

457 p.method = self.method 

458 p.url = self.url 

459 p.headers = self.headers.copy() if self.headers is not None else None # type: ignore[assignment] 

460 p._cookies = _copy_cookie_jar(self._cookies) 

461 p.body = self.body 

462 p.hooks = self.hooks 

463 p._body_position = self._body_position 

464 return p 

465 

466 def prepare_method(self, method: str | None) -> None: 

467 """Prepares the given HTTP method.""" 

468 self.method = method 

469 if self.method is not None: 

470 self.method = to_native_string(self.method.upper()) 

471 

472 @staticmethod 

473 def _get_idna_encoded_host(host: str) -> str: 

474 import idna 

475 

476 try: 

477 host = idna.encode(host, uts46=True).decode("utf-8") 

478 except idna.IDNAError: 

479 raise UnicodeError 

480 return host 

481 

482 def prepare_url( 

483 self, 

484 url: _t.UriType, 

485 params: _t.ParamsType, 

486 ) -> None: 

487 """Prepares the given HTTP URL.""" 

488 #: Accept objects that have string representations. 

489 #: We're unable to blindly call unicode/str functions 

490 #: as this will include the bytestring indicator (b'') 

491 #: on python 3.x. 

492 #: https://github.com/psf/requests/pull/2238 

493 if isinstance(url, bytes): 

494 url = url.decode("utf8") 

495 else: 

496 url = str(url) 

497 

498 # Remove leading whitespaces from url 

499 url = url.lstrip() 

500 

501 # Don't do any URL preparation for non-HTTP schemes like `mailto`, 

502 # `data` etc to work around exceptions from `url_parse`, which 

503 # handles RFC 3986 only. 

504 if ":" in url and not url.lower().startswith("http"): 

505 self.url = url 

506 return 

507 

508 # Support for unicode domain names and paths. 

509 try: 

510 scheme, auth, host, port, path, query, fragment = parse_url(url) 

511 except LocationParseError as e: 

512 raise InvalidURL(*e.args) 

513 

514 if not scheme: 

515 raise MissingSchema( 

516 f"Invalid URL {url!r}: No scheme supplied. " 

517 f"Perhaps you meant https://{url}?" 

518 ) 

519 

520 if not host: 

521 raise InvalidURL(f"Invalid URL {url!r}: No host supplied") 

522 

523 # In general, we want to try IDNA encoding the hostname if the string contains 

524 # non-ASCII characters. This allows users to automatically get the correct IDNA 

525 # behaviour. For strings containing only ASCII characters, we need to also verify 

526 # it doesn't start with a wildcard (*), before allowing the unencoded hostname. 

527 if not unicode_is_ascii(host): 

528 try: 

529 host = self._get_idna_encoded_host(host) 

530 except UnicodeError: 

531 raise InvalidURL("URL has an invalid label.") 

532 elif host.startswith(("*", ".")): 

533 raise InvalidURL("URL has an invalid label.") 

534 

535 # Carefully reconstruct the network location 

536 netloc = auth or "" 

537 if netloc: 

538 netloc += "@" 

539 netloc += host 

540 if port: 

541 netloc += f":{port}" 

542 

543 # Bare domains aren't valid URLs. 

544 if not path: 

545 path = "/" 

546 

547 if isinstance(params, (str, bytes)): 

548 params = to_native_string(params) 

549 

550 if params is not None: 

551 enc_params = self._encode_params(params) 

552 else: 

553 enc_params = "" 

554 

555 if enc_params: 

556 if query: 

557 query = f"{query}&{enc_params}" 

558 else: 

559 query = enc_params 

560 

561 url = requote_uri(urlunparse((scheme, netloc, path, "", query, fragment))) 

562 self.url = url 

563 

564 def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None: 

565 """Prepares the given HTTP headers.""" 

566 

567 self.headers = CaseInsensitiveDict() 

568 if headers: 

569 for header in headers.items(): 

570 # Raise exception on invalid header value. 

571 check_header_validity(header) 

572 name, value = header 

573 self.headers[to_native_string(name)] = value 

574 

575 def prepare_body( 

576 self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None 

577 ) -> None: 

578 """Prepares the given HTTP body data.""" 

579 

580 # Check if file, fo, generator, iterator. 

581 # If not, run through normal process. 

582 

583 # Nottin' on you. 

584 body = None 

585 content_type = None 

586 

587 if not data and json is not None: 

588 # urllib3 requires a bytes-like body. Python 2's json.dumps 

589 # provides this natively, but Python 3 gives a Unicode string. 

590 content_type = "application/json" 

591 

592 try: 

593 body = complexjson.dumps(json, allow_nan=False) 

594 except ValueError as ve: 

595 raise InvalidJSONError(ve, request=self) 

596 

597 if not isinstance(body, bytes): 

598 body = body.encode("utf-8") 

599 

600 # data that proxies attributes to underlying objects needs hasattr 

601 is_iterable = isinstance(data, Iterable) or hasattr(data, "__iter__") 

602 if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)): 

603 try: 

604 length = super_len(data) 

605 except (TypeError, AttributeError, UnsupportedOperation): 

606 length = None 

607 

608 body = data 

609 

610 if getattr(body, "tell", None) is not None: 

611 # Record the current file position before reading. 

612 # This will allow us to rewind a file in the event 

613 # of a redirect. 

614 try: 

615 self._body_position = body.tell() # type: ignore[union-attr] # guarded by getattr check 

616 except OSError: 

617 # This differentiates from None, allowing us to catch 

618 # a failed `tell()` later when trying to rewind the body 

619 self._body_position = object() 

620 

621 if files: 

622 raise NotImplementedError( 

623 "Streamed bodies and files are mutually exclusive." 

624 ) 

625 

626 if length: 

627 self.headers["Content-Length"] = builtin_str(length) 

628 else: 

629 self.headers["Transfer-Encoding"] = "chunked" 

630 else: 

631 # After is_stream filtering, remaining data is raw (not streamed) 

632 raw_data = cast("_t.RawDataType | None", data) 

633 

634 # Multi-part file uploads. 

635 if files: 

636 (body, content_type) = self._encode_files(files, raw_data) 

637 else: 

638 if raw_data: 

639 body = self._encode_params(raw_data) 

640 if isinstance(data, basestring) or isinstance(data, _SupportsRead): 

641 content_type = None 

642 else: 

643 content_type = "application/x-www-form-urlencoded" 

644 

645 self.prepare_content_length(body) 

646 

647 # Add content-type if it wasn't explicitly provided. 

648 if content_type and ("content-type" not in self.headers): 

649 self.headers["Content-Type"] = content_type 

650 

651 self.body = body # type: ignore[assignment] # body transforms from DataType to BodyType 

652 

653 def prepare_content_length(self, body: _t.BodyType) -> None: 

654 """Prepare Content-Length header based on request method and body""" 

655 if body is not None: 

656 length = super_len(body) 

657 if length: 

658 # If length exists, set it. Otherwise, we fallback 

659 # to Transfer-Encoding: chunked. 

660 self.headers["Content-Length"] = builtin_str(length) 

661 elif ( 

662 self.method not in ("GET", "HEAD") 

663 and self.headers.get("Content-Length") is None 

664 ): 

665 # Set Content-Length to 0 for methods that can have a body 

666 # but don't provide one. (i.e. not GET or HEAD) 

667 self.headers["Content-Length"] = "0" 

668 

669 def prepare_auth( 

670 self, 

671 auth: _t.AuthType, 

672 url: _t.UriType = "", 

673 ) -> None: 

674 """Prepares the given HTTP auth data.""" 

675 

676 # If no Auth is explicitly provided, extract it from the URL first. 

677 if auth is None: 

678 url_auth = get_auth_from_url(cast(str, self.url)) 

679 auth = url_auth if any(url_auth) else None 

680 

681 if auth: 

682 if isinstance(auth, tuple) and len(auth) == 2: # type: ignore[arg-type] # pyright widens tuple from Callable in AuthType 

683 # special-case basic HTTP auth 

684 auth_handler = HTTPBasicAuth(*auth) # type: ignore[arg-type] # pyright widens tuple from Callable in AuthType 

685 else: 

686 # TODO: can be fixed by flipping the conditionals 

687 auth_handler = cast("Callable[..., PreparedRequest]", auth) 

688 

689 # Allow auth to make its changes. 

690 r = auth_handler(self) 

691 

692 # Update self to reflect the auth changes. 

693 self.__dict__.update(r.__dict__) 

694 

695 # Recompute Content-Length 

696 self.prepare_content_length(self.body) 

697 

698 def prepare_cookies( 

699 self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None 

700 ) -> None: 

701 """Prepares the given HTTP cookie data. 

702 

703 This function eventually generates a ``Cookie`` header from the 

704 given cookies using cookielib. Due to cookielib's design, the header 

705 will not be regenerated if it already exists, meaning this function 

706 can only be called once for the life of the 

707 :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls 

708 to ``prepare_cookies`` will have no actual effect, unless the "Cookie" 

709 header is removed beforehand. 

710 """ 

711 if isinstance(cookies, cookielib.CookieJar): 

712 self._cookies = cookies 

713 else: 

714 self._cookies = cookiejar_from_dict(cookies) 

715 

716 cookies_jar = cast("CookieJar", self._cookies) 

717 cookie_header = get_cookie_header(cookies_jar, self) 

718 if cookie_header is not None: 

719 self.headers["Cookie"] = cookie_header 

720 

721 def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None: 

722 """Prepares the given hooks.""" 

723 # hooks can be passed as None to the prepare method and to this 

724 # method. To prevent iterating over None, simply use an empty list 

725 # if hooks is False-y 

726 hooks = hooks or {} 

727 for event in hooks: 

728 self.register_hook(event, hooks[event]) 

729 

730 

731class Response: 

732 """The :class:`Response <Response>` object, which contains a 

733 server's response to an HTTP request. 

734 """ 

735 

736 _content: bytes | Literal[False] | None 

737 _content_consumed: bool 

738 _next: PreparedRequest | None 

739 status_code: int 

740 headers: CaseInsensitiveDict[str] 

741 raw: Any 

742 url: str 

743 encoding: str | None 

744 history: list[Response] 

745 reason: str 

746 cookies: RequestsCookieJar 

747 elapsed: datetime.timedelta 

748 request: PreparedRequest 

749 connection: HTTPAdapter 

750 

751 __attrs__: list[str] = [ 

752 "_content", 

753 "status_code", 

754 "headers", 

755 "url", 

756 "history", 

757 "encoding", 

758 "reason", 

759 "cookies", 

760 "elapsed", 

761 "request", 

762 ] 

763 

764 def __init__(self) -> None: 

765 self._content = False 

766 self._content_consumed = False 

767 self._next = None 

768 

769 #: Integer Code of responded HTTP Status, e.g. 404 or 200. 

770 self.status_code = None # type: ignore[assignment] 

771 

772 #: Case-insensitive Dictionary of Response Headers. 

773 #: For example, ``headers['content-encoding']`` will return the 

774 #: value of a ``'Content-Encoding'`` response header. 

775 self.headers = CaseInsensitiveDict() 

776 

777 #: File-like object representation of response (for advanced usage). 

778 #: Use of ``raw`` requires that ``stream=True`` be set on the request. 

779 #: This requirement does not apply for use internally to Requests. 

780 self.raw = None 

781 

782 #: Final URL location of Response. 

783 self.url = None # type: ignore[assignment] 

784 

785 #: Encoding to decode with when accessing r.text. 

786 self.encoding = None 

787 

788 #: A list of :class:`Response <Response>` objects from 

789 #: the history of the Request. Any redirect responses will end 

790 #: up here. The list is sorted from the oldest to the most recent request. 

791 self.history = [] 

792 

793 #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK". 

794 self.reason = None # type: ignore[assignment] 

795 

796 #: A CookieJar of Cookies the server sent back. 

797 self.cookies = cookiejar_from_dict({}) 

798 

799 #: The amount of time elapsed between sending the request 

800 #: and the arrival of the response (as a timedelta). 

801 #: This property specifically measures the time taken between sending 

802 #: the first byte of the request and finishing parsing the headers. It 

803 #: is therefore unaffected by consuming the response content or the 

804 #: value of the ``stream`` keyword argument. 

805 self.elapsed = datetime.timedelta(0) 

806 

807 #: The :class:`PreparedRequest <PreparedRequest>` object to which this 

808 #: is a response. 

809 self.request = None # type: ignore[assignment] 

810 

811 def __enter__(self) -> Self: 

812 return self 

813 

814 def __exit__(self, *args: Any) -> None: 

815 self.close() 

816 

817 def __getstate__(self) -> dict[str, Any]: 

818 # Consume everything; accessing the content attribute makes 

819 # sure the content has been fully read. 

820 if not self._content_consumed: 

821 self.content 

822 

823 return {attr: getattr(self, attr, None) for attr in self.__attrs__} 

824 

825 def __setstate__(self, state: dict[str, Any]) -> None: 

826 for name, value in state.items(): 

827 setattr(self, name, value) 

828 

829 # pickled objects do not have .raw 

830 setattr(self, "_content_consumed", True) 

831 setattr(self, "raw", None) 

832 

833 def __repr__(self) -> str: 

834 return f"<Response [{self.status_code}]>" 

835 

836 def __bool__(self) -> bool: 

837 """Returns True if :attr:`status_code` is less than 400. 

838 

839 This attribute checks if the status code of the response is between 

840 400 and 600 to see if there was a client error or a server error. If 

841 the status code, is between 200 and 400, this will return True. This 

842 is **not** a check to see if the response code is ``200 OK``. 

843 """ 

844 return self.ok 

845 

846 def __nonzero__(self) -> bool: 

847 """Returns True if :attr:`status_code` is less than 400. 

848 

849 This attribute checks if the status code of the response is between 

850 400 and 600 to see if there was a client error or a server error. If 

851 the status code, is between 200 and 400, this will return True. This 

852 is **not** a check to see if the response code is ``200 OK``. 

853 """ 

854 return self.ok 

855 

856 def __iter__(self) -> Iterator[bytes]: 

857 """Allows you to use a response as an iterator.""" 

858 return self.iter_content(128) 

859 

860 @property 

861 def ok(self) -> bool: 

862 """Returns True if :attr:`status_code` is less than 400, False if not. 

863 

864 This attribute checks if the status code of the response is between 

865 400 and 600 to see if there was a client error or a server error. If 

866 the status code is between 200 and 400, this will return True. This 

867 is **not** a check to see if the response code is ``200 OK``. 

868 """ 

869 try: 

870 self.raise_for_status() 

871 except HTTPError: 

872 return False 

873 return True 

874 

875 @property 

876 def is_redirect(self) -> bool: 

877 """True if this Response is a well-formed HTTP redirect that could have 

878 been processed automatically (by :meth:`Session.resolve_redirects`). 

879 """ 

880 return "location" in self.headers and self.status_code in REDIRECT_STATI 

881 

882 @property 

883 def is_permanent_redirect(self) -> bool: 

884 """True if this Response one of the permanent versions of redirect.""" 

885 return "location" in self.headers and self.status_code in ( 

886 codes.moved_permanently, 

887 codes.permanent_redirect, 

888 ) 

889 

890 @property 

891 def next(self) -> PreparedRequest | None: 

892 """Returns a PreparedRequest for the next request in a redirect chain, if there is one.""" 

893 return self._next 

894 

895 @property 

896 def apparent_encoding(self) -> str | None: 

897 """The apparent encoding, provided by the charset_normalizer or chardet libraries.""" 

898 if chardet is not None: 

899 return chardet.detect(self.content)["encoding"] 

900 else: 

901 # If no character detection library is available, we'll fall back 

902 # to a standard Python utf-8 str. 

903 return "utf-8" 

904 

905 @overload 

906 def iter_content( 

907 self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False 

908 ) -> Iterator[bytes]: ... 

909 @overload 

910 def iter_content( 

911 self, chunk_size: int | None = 1, *, decode_unicode: Literal[True] 

912 ) -> Iterator[str | bytes]: ... 

913 def iter_content( 

914 self, chunk_size: int | None = 1, decode_unicode: bool = False 

915 ) -> Iterator[str | bytes]: 

916 """Iterates over the response data. When stream=True is set on the 

917 request, this avoids reading the content at once into memory for 

918 large responses. The chunk size is the number of bytes it should 

919 read into memory. This is not necessarily the length of each item 

920 returned as decoding can take place. 

921 

922 chunk_size must be of type int or None. A value of None will 

923 function differently depending on the value of `stream`. 

924 stream=True will read data as it arrives in whatever size the 

925 chunks are received. If stream=False, data is returned as 

926 a single chunk. 

927 

928 If decode_unicode is True, content will be decoded using encoding 

929 information from the response. If no encoding information is available, 

930 bytes will be returned. This can be bypassed by manually setting 

931 `encoding` on the response. 

932 """ 

933 

934 def generate() -> Generator[bytes, None, None]: 

935 # Special case for urllib3. 

936 if hasattr(self.raw, "stream"): 

937 try: 

938 yield from self.raw.stream(chunk_size, decode_content=True) 

939 except ProtocolError as e: 

940 raise ChunkedEncodingError(e) 

941 except DecodeError as e: 

942 raise ContentDecodingError(e) 

943 except ReadTimeoutError as e: 

944 raise ConnectionError(e) 

945 except SSLError as e: 

946 raise RequestsSSLError(e) 

947 else: 

948 # Standard file-like object. 

949 while True: 

950 chunk = self.raw.read(chunk_size) 

951 if not chunk: 

952 break 

953 yield chunk 

954 

955 self._content_consumed = True 

956 

957 if self._content_consumed and isinstance(self._content, bool): 

958 raise StreamConsumedError() 

959 elif chunk_size is not None and not isinstance(chunk_size, int): # type: ignore[reportUnnecessaryIsInstance] # runtime guard for untyped callers 

960 raise TypeError( 

961 f"chunk_size must be an int, it is instead a {type(chunk_size)}." 

962 ) 

963 

964 if self._content_consumed: 

965 # simulate reading small chunks of the content 

966 content = cast(bytes, self._content) 

967 chunks = iter_slices(content, chunk_size) 

968 else: 

969 chunks = generate() 

970 

971 if decode_unicode: 

972 chunks = stream_decode_response_unicode(chunks, self) 

973 

974 return chunks 

975 

976 @overload 

977 def iter_lines( 

978 self, 

979 chunk_size: int = ITER_CHUNK_SIZE, 

980 decode_unicode: Literal[False] = False, 

981 delimiter: bytes | None = None, 

982 ) -> Iterator[bytes]: ... 

983 @overload 

984 def iter_lines( 

985 self, 

986 chunk_size: int = ITER_CHUNK_SIZE, 

987 *, 

988 decode_unicode: Literal[True], 

989 delimiter: str | bytes | None = None, 

990 ) -> Iterator[str | bytes]: ... 

991 def iter_lines( 

992 self, 

993 chunk_size: int = ITER_CHUNK_SIZE, 

994 decode_unicode: bool = False, 

995 delimiter: str | bytes | None = None, 

996 ) -> Iterator[str | bytes]: 

997 """Iterates over the response data, one line at a time. When 

998 stream=True is set on the request, this avoids reading the 

999 content at once into memory for large responses. 

1000 

1001 The decode_unicode param works the same as in `iter_content`, with the 

1002 same caveats. 

1003 

1004 .. note:: This method is not reentrant safe. 

1005 """ 

1006 

1007 pending: str | bytes | None = None 

1008 

1009 for chunk in self.iter_content( 

1010 chunk_size=chunk_size, decode_unicode=decode_unicode 

1011 ): 

1012 if pending is not None: 

1013 # TODO: remove cast after iter_lines rewrite 

1014 chunk = cast("str | bytes", pending + chunk) 

1015 

1016 if delimiter: 

1017 lines = chunk.split(delimiter) # type: ignore[arg-type] 

1018 else: 

1019 lines = chunk.splitlines() 

1020 

1021 if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: 

1022 pending = lines.pop() 

1023 else: 

1024 pending = None 

1025 

1026 yield from lines 

1027 

1028 if pending is not None: 

1029 yield pending 

1030 

1031 @property 

1032 def content(self) -> bytes: 

1033 """Content of the response, in bytes.""" 

1034 

1035 if self._content is False: 

1036 # Read the contents. 

1037 if self._content_consumed: 

1038 raise RuntimeError("The content for this response was already consumed") 

1039 

1040 if self.status_code == 0 or self.raw is None: 

1041 self._content = None 

1042 else: 

1043 self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b"" 

1044 

1045 self._content_consumed = True 

1046 # don't need to release the connection; that's been handled by urllib3 

1047 # since we exhausted the data. 

1048 return self._content # type: ignore[return-value] 

1049 

1050 @property 

1051 def text(self) -> str: 

1052 """Content of the response, in unicode. 

1053 

1054 If Response.encoding is None, encoding will be guessed using 

1055 ``charset_normalizer`` or ``chardet``. 

1056 

1057 The encoding of the response content is determined based solely on HTTP 

1058 headers, following RFC 2616 to the letter. If you can take advantage of 

1059 non-HTTP knowledge to make a better guess at the encoding, you should 

1060 set ``r.encoding`` appropriately before accessing this property. 

1061 """ 

1062 

1063 # Try charset from content-type 

1064 content = None 

1065 encoding = self.encoding 

1066 

1067 if not self.content: 

1068 return "" 

1069 

1070 # Fallback to auto-detected encoding. 

1071 if self.encoding is None: 

1072 encoding = self.apparent_encoding 

1073 

1074 # Decode unicode from given encoding. 

1075 try: 

1076 content = str(self.content, encoding or "utf-8", errors="replace") 

1077 except (LookupError, TypeError): 

1078 # A LookupError is raised if the encoding was not found which could 

1079 # indicate a misspelling or similar mistake. 

1080 # 

1081 # A TypeError can be raised if encoding is None 

1082 # 

1083 # So we try blindly encoding. 

1084 content = str(self.content, errors="replace") 

1085 

1086 return content 

1087 

1088 def json(self, **kwargs: Any) -> Any: 

1089 r"""Decodes the JSON response body (if any) as a Python object. 

1090 

1091 This may return a dictionary, list, etc. depending on what is in the response. 

1092 

1093 :param \*\*kwargs: Optional arguments that ``json.loads`` takes. 

1094 :raises requests.exceptions.JSONDecodeError: If the response body does not 

1095 contain valid json. 

1096 """ 

1097 

1098 if not self.encoding and self.content and len(self.content) > 3: 

1099 # No encoding set. JSON RFC 4627 section 3 states we should expect 

1100 # UTF-8, -16 or -32. Detect which one to use; If the detection or 

1101 # decoding fails, fall back to `self.text` (using charset_normalizer to make 

1102 # a best guess). 

1103 encoding = guess_json_utf(self.content) 

1104 if encoding is not None: 

1105 try: 

1106 return complexjson.loads(self.content.decode(encoding), **kwargs) 

1107 except UnicodeDecodeError: 

1108 # Wrong UTF codec detected; usually because it's not UTF-8 

1109 # but some other 8-bit codec. This is an RFC violation, 

1110 # and the server didn't bother to tell us what codec *was* 

1111 # used. 

1112 pass 

1113 except JSONDecodeError as e: 

1114 raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) 

1115 

1116 try: 

1117 return complexjson.loads(self.text, **kwargs) 

1118 except JSONDecodeError as e: 

1119 # Catch JSON-related errors and raise as requests.JSONDecodeError 

1120 # This aliases json.JSONDecodeError and simplejson.JSONDecodeError 

1121 raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) 

1122 

1123 @property 

1124 def links(self) -> dict[str, dict[str, str]]: 

1125 """Returns the parsed header links of the response, if any.""" 

1126 

1127 header = self.headers.get("link") 

1128 

1129 resolved_links: dict[str, dict[str, str]] = {} 

1130 

1131 if header: 

1132 links = parse_header_links(header) 

1133 

1134 for link in links: 

1135 key = link.get("rel") or link.get("url") 

1136 if key is not None: 

1137 resolved_links[key] = link 

1138 

1139 return resolved_links 

1140 

1141 def raise_for_status(self) -> None: 

1142 """Raises :class:`HTTPError`, if one occurred.""" 

1143 

1144 http_error_msg = "" 

1145 if isinstance(self.reason, bytes): 

1146 # We attempt to decode utf-8 first because some servers 

1147 # choose to localize their reason strings. If the string 

1148 # isn't utf-8, we fall back to iso-8859-1 for all other 

1149 # encodings. (See PR #3538) 

1150 try: 

1151 reason = self.reason.decode("utf-8") 

1152 except UnicodeDecodeError: 

1153 reason = self.reason.decode("iso-8859-1") 

1154 else: 

1155 reason = self.reason 

1156 

1157 if 400 <= self.status_code < 500: 

1158 http_error_msg = ( 

1159 f"{self.status_code} Client Error: {reason} for url: {self.url}" 

1160 ) 

1161 

1162 elif 500 <= self.status_code < 600: 

1163 http_error_msg = ( 

1164 f"{self.status_code} Server Error: {reason} for url: {self.url}" 

1165 ) 

1166 

1167 if http_error_msg: 

1168 raise HTTPError(http_error_msg, response=self) 

1169 

1170 def close(self) -> None: 

1171 """Releases the connection back to the pool. Once this method has been 

1172 called the underlying ``raw`` object must not be accessed again. 

1173 

1174 *Note: Should not normally need to be called explicitly.* 

1175 """ 

1176 if not self._content_consumed: 

1177 self.raw.close() 

1178 

1179 release_conn = getattr(self.raw, "release_conn", None) 

1180 if release_conn is not None: 

1181 release_conn()