Send HTTP response status and headers. Uses cached status lines and headers for common cases to avoid repeated string formatting and encoding.
(self, status, headers, request)
| 1252 | self._safe_write(response.encode("latin-1")) |
| 1253 | |
| 1254 | def _send_response_start(self, status, headers, request): |
| 1255 | """Send HTTP response status and headers. |
| 1256 | |
| 1257 | Uses cached status lines and headers for common cases to avoid |
| 1258 | repeated string formatting and encoding. |
| 1259 | """ |
| 1260 | # Get cached status line bytes |
| 1261 | reason = self._get_reason_phrase(status) |
| 1262 | status_line = _get_cached_status_line(request.version, status, reason) |
| 1263 | |
| 1264 | # Build headers as bytes directly |
| 1265 | parts = [status_line] |
| 1266 | |
| 1267 | has_date = False |
| 1268 | has_server = False |
| 1269 | |
| 1270 | for name, value in headers: |
| 1271 | if isinstance(name, bytes): |
| 1272 | name_lower = name.lower() |
| 1273 | parts.append(name) |
| 1274 | else: |
| 1275 | name_lower = name.lower().encode("latin-1") |
| 1276 | parts.append(name.encode("latin-1")) |
| 1277 | |
| 1278 | parts.append(b": ") |
| 1279 | |
| 1280 | if isinstance(value, bytes): |
| 1281 | parts.append(value) |
| 1282 | else: |
| 1283 | parts.append(value.encode("latin-1")) |
| 1284 | |
| 1285 | parts.append(b"\r\n") |
| 1286 | |
| 1287 | # Track if Date/Server headers are present |
| 1288 | if name_lower == b"date": |
| 1289 | has_date = True |
| 1290 | elif name_lower == b"server": |
| 1291 | has_server = True |
| 1292 | |
| 1293 | # Add default headers if not present |
| 1294 | if not has_server: |
| 1295 | parts.append(_CACHED_SERVER_HEADER) |
| 1296 | if not has_date: |
| 1297 | parts.append(_get_cached_date_header()) |
| 1298 | |
| 1299 | parts.append(b"\r\n") |
| 1300 | |
| 1301 | # Buffer headers for batching with first body chunk |
| 1302 | self._response_buffer = b"".join(parts) |
| 1303 | |
| 1304 | def _effective_peername(self, peername): |
| 1305 | """Return the client address advertised via PROXY protocol if any. |