Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

72 rader
1.9 KiB

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