responses.py 4.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import importlib
  2. from typing import Any, Protocol, cast
  3. from fastapi.exceptions import FastAPIDeprecationWarning
  4. from fastapi.sse import EventSourceResponse as EventSourceResponse # noqa
  5. from starlette.responses import FileResponse as FileResponse # noqa
  6. from starlette.responses import HTMLResponse as HTMLResponse # noqa
  7. from starlette.responses import JSONResponse as JSONResponse # noqa
  8. from starlette.responses import PlainTextResponse as PlainTextResponse # noqa
  9. from starlette.responses import RedirectResponse as RedirectResponse # noqa
  10. from starlette.responses import Response as Response # noqa
  11. from starlette.responses import StreamingResponse as StreamingResponse # noqa
  12. from typing_extensions import deprecated
  13. class _UjsonModule(Protocol):
  14. def dumps(self, __obj: Any, *, ensure_ascii: bool = ...) -> str: ...
  15. class _OrjsonModule(Protocol):
  16. OPT_NON_STR_KEYS: int
  17. OPT_SERIALIZE_NUMPY: int
  18. def dumps(self, __obj: Any, *, option: int = ...) -> bytes: ...
  19. try:
  20. ujson = cast(_UjsonModule, importlib.import_module("ujson"))
  21. except ModuleNotFoundError: # pragma: nocover
  22. ujson = None # type: ignore[assignment]
  23. try:
  24. orjson = cast(_OrjsonModule, importlib.import_module("orjson"))
  25. except ModuleNotFoundError: # pragma: nocover
  26. orjson = None # type: ignore[assignment]
  27. @deprecated(
  28. "UJSONResponse is deprecated, FastAPI now serializes data directly to JSON "
  29. "bytes via Pydantic when a return type or response model is set, which is "
  30. "faster and doesn't need a custom response class. Read more in the FastAPI "
  31. "docs: https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model "
  32. "and https://fastapi.tiangolo.com/tutorial/response-model/",
  33. category=FastAPIDeprecationWarning,
  34. stacklevel=2,
  35. )
  36. class UJSONResponse(JSONResponse):
  37. """JSON response using the ujson library to serialize data to JSON.
  38. **Deprecated**: `UJSONResponse` is deprecated. FastAPI now serializes data
  39. directly to JSON bytes via Pydantic when a return type or response model is
  40. set, which is faster and doesn't need a custom response class.
  41. Read more in the
  42. [FastAPI docs for Custom Response](https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model)
  43. and the
  44. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  45. **Note**: `ujson` is not included with FastAPI and must be installed
  46. separately, e.g. `pip install ujson`.
  47. """
  48. def render(self, content: Any) -> bytes:
  49. assert ujson is not None, "ujson must be installed to use UJSONResponse"
  50. return ujson.dumps(content, ensure_ascii=False).encode("utf-8")
  51. @deprecated(
  52. "ORJSONResponse is deprecated, FastAPI now serializes data directly to JSON "
  53. "bytes via Pydantic when a return type or response model is set, which is "
  54. "faster and doesn't need a custom response class. Read more in the FastAPI "
  55. "docs: https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model "
  56. "and https://fastapi.tiangolo.com/tutorial/response-model/",
  57. category=FastAPIDeprecationWarning,
  58. stacklevel=2,
  59. )
  60. class ORJSONResponse(JSONResponse):
  61. """JSON response using the orjson library to serialize data to JSON.
  62. **Deprecated**: `ORJSONResponse` is deprecated. FastAPI now serializes data
  63. directly to JSON bytes via Pydantic when a return type or response model is
  64. set, which is faster and doesn't need a custom response class.
  65. Read more in the
  66. [FastAPI docs for Custom Response](https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model)
  67. and the
  68. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  69. **Note**: `orjson` is not included with FastAPI and must be installed
  70. separately, e.g. `pip install orjson`.
  71. """
  72. def render(self, content: Any) -> bytes:
  73. assert orjson is not None, "orjson must be installed to use ORJSONResponse"
  74. return orjson.dumps(
  75. content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY
  76. )