-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Open
Labels
Description
Is your feature request related to a problem?
When we are overriding json_serialize callable argument in ClientSession constructor, it requires JSONEncoder callable type to return a str type. I think this is overly restrictive when we eventually encode this to bytes to be used as body payload.
There are many publicly available JSON serializer that directly dumps into bytes type. I think we should update to also allow JSONEncoder callable to return bytes type and skip calling str.encode.
Describe the solution you'd like
Line 17 in 7b4db6f
| JSONEncoder = Callable[[Any], str] |
# aiohttp/typedefs.py
JSONEncoder = Callable[[Any], str | bytes]
# aiohttp/payload.py
class JsonPayload(BytesPayload):
def __init__(
self,
value: Any,
encoding: str = "utf-8",
content_type: str = "application/json",
dumps: JSONEncoder = json.dumps,
*args: Any,
**kwargs: Any,
) -> None:
dumped = dumps(value)
if isinstance(dumped, str):
dumped = dumped.encode(encoding)
super().__init__(
dumps(value).encode(encoding),
content_type=content_type,
encoding=encoding,
*args,
**kwargs,
)Describe alternatives you've considered
I can obviously do this for now, but this is just doing decoding to str, then encoding back to bytes unnecessarily.
existing_serializer: Callable[[Any], bytes]
ClientSession(
...,
json_serialize=lambda o: existing_serializer(o).decode()
...
)
Related component
Client
Additional context
No response
Code of Conduct
- I agree to follow the aio-libs Code of Conduct
Reactions are currently unavailable