Skip to content

Commit e58241a

Browse files
committed
chore: support JSONRepsonse dumps callable return type bytes
the `dumps` parameter is used to serialize the `JSONResponse` to text. this is often done with python's built in `json.dumps` but other times via `orjson.dumps` however, to use `orjson.dumps`, you have to ignore the suggested type (`str`) because `orjson.dumps` returns a `bytes` to correct this, the typing for the dumps callable has been switched to be an `AnyStr` so either `bytes` or `str` returning callable can be passed
1 parent da1c646 commit e58241a

File tree

2 files changed

+10
-8
lines changed

2 files changed

+10
-8
lines changed

sanic/response/convenience.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def json(
3838
status: int = 200,
3939
headers: Optional[Dict[str, str]] = None,
4040
content_type: str = "application/json",
41-
dumps: Optional[Callable[..., str]] = None,
41+
dumps: Optional[Callable[..., AnyStr]] = None,
4242
**kwargs: Any,
4343
) -> JSONResponse:
4444
"""Returns response object with body in json format.
@@ -48,7 +48,7 @@ def json(
4848
status (int, optional): HTTP response code. Defaults to `200`.
4949
headers (Dict[str, str], optional): Custom HTTP headers. Defaults to `None`.
5050
content_type (str, optional): The content type (string) of the response. Defaults to `"application/json"`.
51-
dumps (Callable[..., str], optional): A custom json dumps function. Defaults to `None`.
51+
dumps (Callable[..., AnyStr], optional): A custom json dumps function. Defaults to `None`.
5252
**kwargs (Any): Remaining arguments that are passed to the json encoder.
5353
5454
Returns:

sanic/response/types.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def __repr__(self):
5959
class_name = self.__class__.__name__
6060
return f"<{class_name}: {self.status} {self.content_type}>"
6161

62-
def _encode_body(self, data: Optional[AnyStr]):
62+
def _encode_body(self, data: Optional[str | bytes]):
6363
if data is None:
6464
return b""
6565
return data.encode() if hasattr(data, "encode") else data # type: ignore
@@ -264,7 +264,7 @@ class JSONResponse(HTTPResponse):
264264
status (int, optional): HTTP response number. Defaults to `200`.
265265
headers (Optional[Union[Header, Dict[str, str]]], optional): Headers to be returned. Defaults to `None`.
266266
content_type (str, optional): Content type to be returned (as a header). Defaults to `"application/json"`.
267-
dumps (Optional[Callable[..., str]], optional): The function to use for json encoding. Defaults to `None`.
267+
dumps (Optional[Callable[..., AnyStr]], optional): The function to use for json encoding. Defaults to `None`.
268268
**kwargs (Any, optional): The kwargs to pass to the json encoding function. Defaults to `{}`.
269269
""" # noqa: E501
270270

@@ -283,13 +283,15 @@ def __init__(
283283
status: int = 200,
284284
headers: Optional[Union[Header, Dict[str, str]]] = None,
285285
content_type: str = "application/json",
286-
dumps: Optional[Callable[..., str]] = None,
286+
dumps: Optional[Callable[..., AnyStr]] = None,
287287
**kwargs: Any,
288288
):
289289
self._initialized = False
290290
self._body_manually_set = False
291291

292-
self._use_dumps = dumps or BaseHTTPResponse._dumps
292+
self._use_dumps: Callable[..., str | bytes] = (
293+
dumps or BaseHTTPResponse._dumps
294+
)
293295
self._use_dumps_kwargs = kwargs
294296

295297
self._raw_body = body
@@ -352,7 +354,7 @@ def body(self, value: Optional[bytes]):
352354
def set_body(
353355
self,
354356
body: Any,
355-
dumps: Optional[Callable[..., str]] = None,
357+
dumps: Optional[Callable[..., AnyStr]] = None,
356358
**dumps_kwargs: Any,
357359
) -> None:
358360
"""Set the response body to the given value, using the given dumps function
@@ -363,7 +365,7 @@ def set_body(
363365
364366
Args:
365367
body (Any): The body to set
366-
dumps (Optional[Callable[..., str]], optional): The function to use for json encoding. Defaults to `None`.
368+
dumps (Optional[Callable[..., AnyStr]], optional): The function to use for json encoding. Defaults to `None`.
367369
**dumps_kwargs (Any, optional): The kwargs to pass to the json encoding function. Defaults to `{}`.
368370
369371
Examples:

0 commit comments

Comments
 (0)