| 53 | return content.encode(self.charset) # type: ignore |
| 54 | |
| 55 | def init_headers(self, headers: Mapping[str, str] | None = None) -> None: |
| 56 | if headers is None: |
| 57 | raw_headers: list[tuple[bytes, bytes]] = [] |
| 58 | populate_content_length = True |
| 59 | populate_content_type = True |
| 60 | else: |
| 61 | raw_headers = [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers.items()] |
| 62 | keys = [h[0] for h in raw_headers] |
| 63 | populate_content_length = b"content-length" not in keys |
| 64 | populate_content_type = b"content-type" not in keys |
| 65 | |
| 66 | body = getattr(self, "body", None) |
| 67 | if ( |
| 68 | body is not None |
| 69 | and populate_content_length |
| 70 | and not (self.status_code < 200 or self.status_code in (204, 304)) |
| 71 | ): |
| 72 | content_length = str(len(body)) |
| 73 | raw_headers.append((b"content-length", content_length.encode("latin-1"))) |
| 74 | |
| 75 | content_type = self.media_type |
| 76 | if content_type is not None and populate_content_type: |
| 77 | if content_type.startswith("text/") and "charset=" not in content_type.lower(): |
| 78 | content_type += "; charset=" + self.charset |
| 79 | raw_headers.append((b"content-type", content_type.encode("latin-1"))) |
| 80 | |
| 81 | self.raw_headers = raw_headers |
| 82 | |
| 83 | @property |
| 84 | def headers(self) -> MutableHeaders: |