Debian Codegraph @

src/websockets/legacy/exceptions.py

raw
1 import http
2
3 from .. import datastructures
4 from ..exceptions import (
5 InvalidHandshake,
6 # InvalidMessage was incorrectly moved here in versions 14.0 and 14.1.
7 InvalidMessage, # noqa: F401
8 ProtocolError as WebSocketProtocolError, # noqa: F401
9 )
10 from ..typing import StatusLike
11
12
13 class InvalidStatusCode(InvalidHandshake):
14 """
15 Raised when a handshake response status code is invalid.
16
17 """
18
19 def __init__(self, status_code: int, headers: datastructures.Headers) -> None:
20 self.status_code = status_code
21 self.headers = headers
22
23 def __str__(self) -> str:
24 return f"server rejected WebSocket connection: HTTP {self.status_code}"
25
26
27 class AbortHandshake(InvalidHandshake):
28 """
29 Raised to abort the handshake on purpose and return an HTTP response.
30
31 This exception is an implementation detail.
32
33 The public API is
34 :meth:`~websockets.legacy.server.WebSocketServerProtocol.process_request`.
35
36 Attributes:
37 status (~http.HTTPStatus): HTTP status code.
38 headers (Headers): HTTP response headers.
39 body (bytes): HTTP response body.
40 """
41
42 def __init__(
43 self,
44 status: StatusLike,
45 headers: datastructures.HeadersLike,
46 body: bytes = b"",
47 ) -> None:
48 # If a user passes an int instead of an HTTPStatus, fix it automatically.
49 self.status = http.HTTPStatus(status)
50 self.headers = datastructures.Headers(headers)
51 self.body = body
52
53 def __str__(self) -> str:
54 return (
55 f"HTTP {self.status:d}, {len(self.headers)} headers, {len(self.body)} bytes"
56 )
57
58
59 class RedirectHandshake(InvalidHandshake):
60 """
61 Raised when a handshake gets redirected.
62
63 This exception is an implementation detail.
64
65 """
66
67 def __init__(self, uri: str) -> None:
68 self.uri = uri
69
70 def __str__(self) -> str:
71 return f"redirect to {self.uri}"