Send and log an error reply. Arguments are * code: an HTTP error code 3 digits * message: a simple optional 1 line reason phrase. *( HTAB / SP / VCHAR / %x80-FF ) defaults to short entry matching the response code
(self, code, message=None, explain=None)
| 498 | self.handle_one_request() |
| 499 | |
| 500 | def send_error(self, code, message=None, explain=None): |
| 501 | """Send and log an error reply. |
| 502 | |
| 503 | Arguments are |
| 504 | * code: an HTTP error code |
| 505 | 3 digits |
| 506 | * message: a simple optional 1 line reason phrase. |
| 507 | *( HTAB / SP / VCHAR / %x80-FF ) |
| 508 | defaults to short entry matching the response code |
| 509 | * explain: a detailed message defaults to the long entry |
| 510 | matching the response code. |
| 511 | |
| 512 | This sends an error response (so it must be called before any |
| 513 | output has been generated), logs the error, and finally sends |
| 514 | a piece of HTML explaining the error to the user. |
| 515 | |
| 516 | """ |
| 517 | |
| 518 | try: |
| 519 | shortmsg, longmsg = self.responses[code] |
| 520 | except KeyError: |
| 521 | shortmsg, longmsg = '???', '???' |
| 522 | if message is None: |
| 523 | message = shortmsg |
| 524 | if explain is None: |
| 525 | explain = longmsg |
| 526 | self.log_error("code %d, message %s", code, message) |
| 527 | self.send_response(code, message) |
| 528 | self.send_header('Connection', 'close') |
| 529 | |
| 530 | # Message body is omitted for cases described in: |
| 531 | # - RFC7230: 3.3. 1xx, 204(No Content), 304(Not Modified) |
| 532 | # - RFC7231: 6.3.6. 205(Reset Content) |
| 533 | body = None |
| 534 | if (code >= 200 and |
| 535 | code not in (HTTPStatus.NO_CONTENT, |
| 536 | HTTPStatus.RESET_CONTENT, |
| 537 | HTTPStatus.NOT_MODIFIED)): |
| 538 | # HTML encode to prevent Cross Site Scripting attacks |
| 539 | # (see bug #1100201) |
| 540 | content = (self.error_message_format % { |
| 541 | 'code': code, |
| 542 | 'message': html.escape(message, quote=False), |
| 543 | 'explain': html.escape(explain, quote=False) |
| 544 | }) |
| 545 | body = content.encode('UTF-8', 'replace') |
| 546 | self.send_header("Content-Type", self.error_content_type) |
| 547 | self.send_header('Content-Length', str(len(body))) |
| 548 | self.end_headers() |
| 549 | |
| 550 | if self.command != 'HEAD' and body: |
| 551 | self.wfile.write(body) |
| 552 | |
| 553 | def send_response(self, code, message=None): |
| 554 | """Add the response header to the headers buffer and log the |