Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: support JSONRepsonse dumps callable return type bytes #3000

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions sanic/response/convenience.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def json(
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "application/json",
dumps: Optional[Callable[..., str]] = None,
dumps: Optional[Callable[..., AnyStr]] = None,
**kwargs: Any,
) -> JSONResponse:
"""Returns response object with body in json format.
Expand All @@ -48,7 +48,7 @@ def json(
status (int, optional): HTTP response code. Defaults to `200`.
headers (Dict[str, str], optional): Custom HTTP headers. Defaults to `None`.
content_type (str, optional): The content type (string) of the response. Defaults to `"application/json"`.
dumps (Callable[..., str], optional): A custom json dumps function. Defaults to `None`.
dumps (Callable[..., AnyStr], optional): A custom json dumps function. Defaults to `None`.
**kwargs (Any): Remaining arguments that are passed to the json encoder.

Returns:
Expand Down
14 changes: 8 additions & 6 deletions sanic/response/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def __repr__(self):
class_name = self.__class__.__name__
return f"<{class_name}: {self.status} {self.content_type}>"

def _encode_body(self, data: Optional[AnyStr]):
def _encode_body(self, data: Optional[str | bytes]):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was an odd change - without this, everything complained that it should be Sequence[object]?

sanic/response/types.py:334: error: Value of type variable "AnyStr" of "_encode_body" of "BaseHTTPResponse" cannot be "Sequence[object]"  [type-var]

Unfortunately, not familiar enough with mypy for this.

if data is None:
return b""
return data.encode() if hasattr(data, "encode") else data # type: ignore
Expand Down Expand Up @@ -264,7 +264,7 @@ class JSONResponse(HTTPResponse):
status (int, optional): HTTP response number. Defaults to `200`.
headers (Optional[Union[Header, Dict[str, str]]], optional): Headers to be returned. Defaults to `None`.
content_type (str, optional): Content type to be returned (as a header). Defaults to `"application/json"`.
dumps (Optional[Callable[..., str]], optional): The function to use for json encoding. Defaults to `None`.
dumps (Optional[Callable[..., AnyStr]], optional): The function to use for json encoding. Defaults to `None`.
**kwargs (Any, optional): The kwargs to pass to the json encoding function. Defaults to `{}`.
""" # noqa: E501

Expand All @@ -283,13 +283,15 @@ def __init__(
status: int = 200,
headers: Optional[Union[Header, Dict[str, str]]] = None,
content_type: str = "application/json",
dumps: Optional[Callable[..., str]] = None,
dumps: Optional[Callable[..., AnyStr]] = None,
**kwargs: Any,
):
self._initialized = False
self._body_manually_set = False

self._use_dumps = dumps or BaseHTTPResponse._dumps
self._use_dumps: Callable[..., str | bytes] = (
dumps or BaseHTTPResponse._dumps
)
self._use_dumps_kwargs = kwargs

self._raw_body = body
Expand Down Expand Up @@ -352,7 +354,7 @@ def body(self, value: Optional[bytes]):
def set_body(
self,
body: Any,
dumps: Optional[Callable[..., str]] = None,
dumps: Optional[Callable[..., AnyStr]] = None,
**dumps_kwargs: Any,
) -> None:
"""Set the response body to the given value, using the given dumps function
Expand All @@ -363,7 +365,7 @@ def set_body(

Args:
body (Any): The body to set
dumps (Optional[Callable[..., str]], optional): The function to use for json encoding. Defaults to `None`.
dumps (Optional[Callable[..., AnyStr]], optional): The function to use for json encoding. Defaults to `None`.
**dumps_kwargs (Any, optional): The kwargs to pass to the json encoding function. Defaults to `{}`.

Examples:
Expand Down
Loading