You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

177 line
4.9 KiB

  1. from typing import Any, Dict, Optional, Sequence, Type, Union
  2. from pydantic import BaseModel, create_model
  3. from starlette.exceptions import HTTPException as StarletteHTTPException
  4. from starlette.exceptions import WebSocketException as StarletteWebSocketException
  5. from typing_extensions import Annotated, Doc
  6. class HTTPException(StarletteHTTPException):
  7. """
  8. An HTTP exception you can raise in your own code to show errors to the client.
  9. This is for client errors, invalid authentication, invalid data, etc. Not for server
  10. errors in your code.
  11. Read more about it in the
  12. [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
  13. ## Example
  14. ```python
  15. from fastapi import FastAPI, HTTPException
  16. app = FastAPI()
  17. items = {"foo": "The Foo Wrestlers"}
  18. @app.get("/items/{item_id}")
  19. async def read_item(item_id: str):
  20. if item_id not in items:
  21. raise HTTPException(status_code=404, detail="Item not found")
  22. return {"item": items[item_id]}
  23. ```
  24. """
  25. def __init__(
  26. self,
  27. status_code: Annotated[
  28. int,
  29. Doc(
  30. """
  31. HTTP status code to send to the client.
  32. """
  33. ),
  34. ],
  35. detail: Annotated[
  36. Any,
  37. Doc(
  38. """
  39. Any data to be sent to the client in the `detail` key of the JSON
  40. response.
  41. """
  42. ),
  43. ] = None,
  44. headers: Annotated[
  45. Optional[Dict[str, str]],
  46. Doc(
  47. """
  48. Any headers to send to the client in the response.
  49. """
  50. ),
  51. ] = None,
  52. ) -> None:
  53. super().__init__(status_code=status_code, detail=detail, headers=headers)
  54. class WebSocketException(StarletteWebSocketException):
  55. """
  56. A WebSocket exception you can raise in your own code to show errors to the client.
  57. This is for client errors, invalid authentication, invalid data, etc. Not for server
  58. errors in your code.
  59. Read more about it in the
  60. [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
  61. ## Example
  62. ```python
  63. from typing import Annotated
  64. from fastapi import (
  65. Cookie,
  66. FastAPI,
  67. WebSocket,
  68. WebSocketException,
  69. status,
  70. )
  71. app = FastAPI()
  72. @app.websocket("/items/{item_id}/ws")
  73. async def websocket_endpoint(
  74. *,
  75. websocket: WebSocket,
  76. session: Annotated[str | None, Cookie()] = None,
  77. item_id: str,
  78. ):
  79. if session is None:
  80. raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
  81. await websocket.accept()
  82. while True:
  83. data = await websocket.receive_text()
  84. await websocket.send_text(f"Session cookie is: {session}")
  85. await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
  86. ```
  87. """
  88. def __init__(
  89. self,
  90. code: Annotated[
  91. int,
  92. Doc(
  93. """
  94. A closing code from the
  95. [valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1).
  96. """
  97. ),
  98. ],
  99. reason: Annotated[
  100. Union[str, None],
  101. Doc(
  102. """
  103. The reason to close the WebSocket connection.
  104. It is UTF-8-encoded data. The interpretation of the reason is up to the
  105. application, it is not specified by the WebSocket specification.
  106. It could contain text that could be human-readable or interpretable
  107. by the client code, etc.
  108. """
  109. ),
  110. ] = None,
  111. ) -> None:
  112. super().__init__(code=code, reason=reason)
  113. RequestErrorModel: Type[BaseModel] = create_model("Request")
  114. WebSocketErrorModel: Type[BaseModel] = create_model("WebSocket")
  115. class FastAPIError(RuntimeError):
  116. """
  117. A generic, FastAPI-specific error.
  118. """
  119. class ValidationException(Exception):
  120. def __init__(self, errors: Sequence[Any]) -> None:
  121. self._errors = errors
  122. def errors(self) -> Sequence[Any]:
  123. return self._errors
  124. class RequestValidationError(ValidationException):
  125. def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:
  126. super().__init__(errors)
  127. self.body = body
  128. class WebSocketRequestValidationError(ValidationException):
  129. pass
  130. class ResponseValidationError(ValidationException):
  131. def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:
  132. super().__init__(errors)
  133. self.body = body
  134. def __str__(self) -> str:
  135. message = f"{len(self._errors)} validation errors:\n"
  136. for err in self._errors:
  137. message += f" {err}\n"
  138. return message