From 235cdca7db3c0377a28d867c61efc1073a2fbefd Mon Sep 17 00:00:00 2001 From: xiayouran Date: Wed, 22 Nov 2023 17:00:09 +0800 Subject: [PATCH 1/2] fix func send_json to support chinese --- starlette/testclient.py | 2 +- starlette/websockets.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/starlette/testclient.py b/starlette/testclient.py index a0046f2ff..163e5b67e 100644 --- a/starlette/testclient.py +++ b/starlette/testclient.py @@ -147,7 +147,7 @@ def send_bytes(self, data: bytes) -> None: def send_json(self, data: typing.Any, mode: str = "text") -> None: assert mode in ["text", "binary"] - text = json.dumps(data, separators=(",", ":")) + text = json.dumps(data, separators=(",", ":"), ensure_ascii=False) if mode == "text": self.send({"type": "websocket.receive", "text": text}) else: diff --git a/starlette/websockets.py b/starlette/websockets.py index 859560857..a34bc1339 100644 --- a/starlette/websockets.py +++ b/starlette/websockets.py @@ -168,7 +168,7 @@ async def send_bytes(self, data: bytes) -> None: async def send_json(self, data: typing.Any, mode: str = "text") -> None: if mode not in {"text", "binary"}: raise RuntimeError('The "mode" argument should be "text" or "binary".') - text = json.dumps(data, separators=(",", ":")) + text = json.dumps(data, separators=(",", ":"), ensure_ascii=False) if mode == "text": await self.send({"type": "websocket.send", "text": text}) else: From 5b59a3c0145283e68aa53dce3a987116572e6cd6 Mon Sep 17 00:00:00 2001 From: Marcelo Trylesinski Date: Fri, 1 Dec 2023 13:15:55 +0000 Subject: [PATCH 2/2] Add test --- tests/test_websockets.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/test_websockets.py b/tests/test_websockets.py index 65e16671d..2b487633e 100644 --- a/tests/test_websockets.py +++ b/tests/test_websockets.py @@ -39,6 +39,24 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None: assert data == {"test": "data"} +def test_websocket_ensure_unicode_on_send_json( + test_client_factory: Callable[..., TestClient] +): + async def app(scope: Scope, receive: Receive, send: Send) -> None: + websocket = WebSocket(scope, receive=receive, send=send) + + await websocket.accept() + message = await websocket.receive_json(mode="text") + await websocket.send_json(message, mode="text") + await websocket.close() + + client = test_client_factory(app) + with client.websocket_connect("/123?a=abc") as websocket: + websocket.send_json({"test": "数据"}, mode="text") + data = websocket.receive_text() + assert data == '{"test":"数据"}' + + def test_websocket_query_params(test_client_factory): async def app(scope: Scope, receive: Receive, send: Send) -> None: websocket = WebSocket(scope, receive=receive, send=send)