Simplified API for creating request objects.
(
cls,
method: str,
url: str,
content: bytes | str = "",
headers: (
Headers | dict[str | bytes, str | bytes] | Iterable[tuple[bytes, bytes]]
) = (),
)
| 581 | |
| 582 | @classmethod |
| 583 | def make( |
| 584 | cls, |
| 585 | method: str, |
| 586 | url: str, |
| 587 | content: bytes | str = "", |
| 588 | headers: ( |
| 589 | Headers | dict[str | bytes, str | bytes] | Iterable[tuple[bytes, bytes]] |
| 590 | ) = (), |
| 591 | ) -> "Request": |
| 592 | """ |
| 593 | Simplified API for creating request objects. |
| 594 | """ |
| 595 | # Headers can be list or dict, we differentiate here. |
| 596 | if isinstance(headers, Headers): |
| 597 | pass |
| 598 | elif isinstance(headers, dict): |
| 599 | headers = Headers( |
| 600 | ( |
| 601 | always_bytes(k, "utf-8", "surrogateescape"), |
| 602 | always_bytes(v, "utf-8", "surrogateescape"), |
| 603 | ) |
| 604 | for k, v in headers.items() |
| 605 | ) |
| 606 | elif isinstance(headers, Iterable): |
| 607 | headers = Headers(headers) # type: ignore |
| 608 | else: |
| 609 | raise TypeError( |
| 610 | "Expected headers to be an iterable or dict, but is {}.".format( |
| 611 | type(headers).__name__ |
| 612 | ) |
| 613 | ) |
| 614 | |
| 615 | req = cls( |
| 616 | "", |
| 617 | 0, |
| 618 | method.encode("utf-8", "surrogateescape"), |
| 619 | b"", |
| 620 | b"", |
| 621 | b"", |
| 622 | b"HTTP/1.1", |
| 623 | headers, |
| 624 | b"", |
| 625 | None, |
| 626 | time.time(), |
| 627 | time.time(), |
| 628 | ) |
| 629 | |
| 630 | req.url = url |
| 631 | # Assign this manually to update the content-length header. |
| 632 | if isinstance(content, bytes): |
| 633 | req.content = content |
| 634 | elif isinstance(content, str): |
| 635 | req.text = content |
| 636 | else: |
| 637 | raise TypeError( |
| 638 | f"Expected content to be str or bytes, but is {type(content).__name__}." |
| 639 | ) |
| 640 |