Simplified API for creating response objects.
(
cls,
status_code: int = 200,
content: bytes | str = b"",
headers: (
Headers | Mapping[str, str | bytes] | Iterable[tuple[bytes, bytes]]
) = (),
)
| 1063 | |
| 1064 | @classmethod |
| 1065 | def make( |
| 1066 | cls, |
| 1067 | status_code: int = 200, |
| 1068 | content: bytes | str = b"", |
| 1069 | headers: ( |
| 1070 | Headers | Mapping[str, str | bytes] | Iterable[tuple[bytes, bytes]] |
| 1071 | ) = (), |
| 1072 | ) -> "Response": |
| 1073 | """ |
| 1074 | Simplified API for creating response objects. |
| 1075 | """ |
| 1076 | if isinstance(headers, Headers): |
| 1077 | headers = headers |
| 1078 | elif isinstance(headers, dict): |
| 1079 | headers = Headers( |
| 1080 | ( |
| 1081 | always_bytes(k, "utf-8", "surrogateescape"), # type: ignore |
| 1082 | always_bytes(v, "utf-8", "surrogateescape"), |
| 1083 | ) |
| 1084 | for k, v in headers.items() |
| 1085 | ) |
| 1086 | elif isinstance(headers, Iterable): |
| 1087 | headers = Headers(headers) # type: ignore |
| 1088 | else: |
| 1089 | raise TypeError( |
| 1090 | "Expected headers to be an iterable or dict, but is {}.".format( |
| 1091 | type(headers).__name__ |
| 1092 | ) |
| 1093 | ) |
| 1094 | |
| 1095 | resp = cls( |
| 1096 | b"HTTP/1.1", |
| 1097 | status_code, |
| 1098 | status_codes.RESPONSES.get(status_code, "").encode(), |
| 1099 | headers, |
| 1100 | None, |
| 1101 | None, |
| 1102 | time.time(), |
| 1103 | time.time(), |
| 1104 | ) |
| 1105 | |
| 1106 | # Assign this manually to update the content-length header. |
| 1107 | if isinstance(content, bytes): |
| 1108 | resp.content = content |
| 1109 | elif isinstance(content, str): |
| 1110 | resp.text = content |
| 1111 | else: |
| 1112 | raise TypeError( |
| 1113 | f"Expected content to be str or bytes, but is {type(content).__name__}." |
| 1114 | ) |
| 1115 | |
| 1116 | return resp |
| 1117 | |
| 1118 | @property |
| 1119 | def status_code(self) -> int: |