Prepares the given HTTP URL.
(
self,
url: _t.UriType,
params: _t.ParamsType,
)
| 479 | return host |
| 480 | |
| 481 | def prepare_url( |
| 482 | self, |
| 483 | url: _t.UriType, |
| 484 | params: _t.ParamsType, |
| 485 | ) -> None: |
| 486 | """Prepares the given HTTP URL.""" |
| 487 | #: Accept objects that have string representations. |
| 488 | #: We're unable to blindly call unicode/str functions |
| 489 | #: as this will include the bytestring indicator (b'') |
| 490 | #: on python 3.x. |
| 491 | #: https://github.com/psf/requests/pull/2238 |
| 492 | if isinstance(url, bytes): |
| 493 | url = url.decode("utf8") |
| 494 | else: |
| 495 | url = str(url) |
| 496 | |
| 497 | # Remove leading whitespaces from url |
| 498 | url = url.lstrip() |
| 499 | |
| 500 | # Don't do any URL preparation for non-HTTP schemes like `mailto`, |
| 501 | # `data` etc to work around exceptions from `url_parse`, which |
| 502 | # handles RFC 3986 only. |
| 503 | if ":" in url and not url.lower().startswith("http"): |
| 504 | self.url = url |
| 505 | return |
| 506 | |
| 507 | # Support for unicode domain names and paths. |
| 508 | try: |
| 509 | scheme, auth, host, port, path, query, fragment = parse_url(url) |
| 510 | except LocationParseError as e: |
| 511 | raise InvalidURL(*e.args) |
| 512 | |
| 513 | if not scheme: |
| 514 | raise MissingSchema( |
| 515 | f"Invalid URL {url!r}: No scheme supplied. " |
| 516 | f"Perhaps you meant https://{url}?" |
| 517 | ) |
| 518 | |
| 519 | if not host: |
| 520 | raise InvalidURL(f"Invalid URL {url!r}: No host supplied") |
| 521 | |
| 522 | # In general, we want to try IDNA encoding the hostname if the string contains |
| 523 | # non-ASCII characters. This allows users to automatically get the correct IDNA |
| 524 | # behaviour. For strings containing only ASCII characters, we need to also verify |
| 525 | # it doesn't start with a wildcard (*), before allowing the unencoded hostname. |
| 526 | if not unicode_is_ascii(host): |
| 527 | try: |
| 528 | host = self._get_idna_encoded_host(host) |
| 529 | except UnicodeError: |
| 530 | raise InvalidURL("URL has an invalid label.") |
| 531 | elif host.startswith(("*", ".")): |
| 532 | raise InvalidURL("URL has an invalid label.") |
| 533 | |
| 534 | # Carefully reconstruct the network location |
| 535 | netloc = auth or "" |
| 536 | if netloc: |
| 537 | netloc += "@" |
| 538 | netloc += host |
no test coverage detected