Coverage for fastapi/responses.py: 100%

20 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-12-04 08:29 +0000

1from typing import Any 1abcdefg

2 

3from starlette.responses import FileResponse as FileResponse # noqa 1abcdefg

4from starlette.responses import HTMLResponse as HTMLResponse # noqa 1abcdefg

5from starlette.responses import JSONResponse as JSONResponse # noqa 1abcdefg

6from starlette.responses import PlainTextResponse as PlainTextResponse # noqa 1abcdefg

7from starlette.responses import RedirectResponse as RedirectResponse # noqa 1abcdefg

8from starlette.responses import Response as Response # noqa 1abcdefg

9from starlette.responses import StreamingResponse as StreamingResponse # noqa 1abcdefg

10 

11try: 1abcdefg

12 import ujson 1abcdefg

13except ImportError: # pragma: nocover 

14 ujson = None # type: ignore 

15 

16 

17try: 1abcdefg

18 import orjson 1abcdefg

19except ImportError: # pragma: nocover 

20 orjson = None # type: ignore 

21 

22 

23class UJSONResponse(JSONResponse): 1abcdefg

24 """ 

25 JSON response using the high-performance ujson library to serialize data to JSON. 

26 

27 Read more about it in the 

28 [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/). 

29 """ 

30 

31 def render(self, content: Any) -> bytes: 1abcdefg

32 assert ujson is not None, "ujson must be installed to use UJSONResponse" 1hijklmn

33 return ujson.dumps(content, ensure_ascii=False).encode("utf-8") 1hijklmn

34 

35 

36class ORJSONResponse(JSONResponse): 1abcdefg

37 """ 

38 JSON response using the high-performance orjson library to serialize data to JSON. 

39 

40 Read more about it in the 

41 [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/). 

42 """ 

43 

44 def render(self, content: Any) -> bytes: 1abcdefg

45 assert orjson is not None, "orjson must be installed to use ORJSONResponse" 1opqrstuvwxyzAB

46 return orjson.dumps( 1opqrstuvwxyzAB

47 content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY 

48 )