Skip to content

Commit a1ee8b4

Browse files
xiayouranKludex
andauthored
Set ensure_ascii=False on json.dumps() for WebSocket.send_json() (#2341)
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
1 parent 811dacc commit a1ee8b4

3 files changed

Lines changed: 20 additions & 2 deletions

File tree

starlette/testclient.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ def send_bytes(self, data: bytes) -> None:
147147

148148
def send_json(self, data: typing.Any, mode: str = "text") -> None:
149149
assert mode in ["text", "binary"]
150-
text = json.dumps(data, separators=(",", ":"))
150+
text = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
151151
if mode == "text":
152152
self.send({"type": "websocket.receive", "text": text})
153153
else:

starlette/websockets.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ async def send_bytes(self, data: bytes) -> None:
168168
async def send_json(self, data: typing.Any, mode: str = "text") -> None:
169169
if mode not in {"text", "binary"}:
170170
raise RuntimeError('The "mode" argument should be "text" or "binary".')
171-
text = json.dumps(data, separators=(",", ":"))
171+
text = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
172172
if mode == "text":
173173
await self.send({"type": "websocket.send", "text": text})
174174
else:

tests/test_websockets.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,24 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
3939
assert data == {"test": "data"}
4040

4141

42+
def test_websocket_ensure_unicode_on_send_json(
43+
test_client_factory: Callable[..., TestClient]
44+
):
45+
async def app(scope: Scope, receive: Receive, send: Send) -> None:
46+
websocket = WebSocket(scope, receive=receive, send=send)
47+
48+
await websocket.accept()
49+
message = await websocket.receive_json(mode="text")
50+
await websocket.send_json(message, mode="text")
51+
await websocket.close()
52+
53+
client = test_client_factory(app)
54+
with client.websocket_connect("/123?a=abc") as websocket:
55+
websocket.send_json({"test": "数据"}, mode="text")
56+
data = websocket.receive_text()
57+
assert data == '{"test":"数据"}'
58+
59+
4260
def test_websocket_query_params(test_client_factory):
4361
async def app(scope: Scope, receive: Receive, send: Send) -> None:
4462
websocket = WebSocket(scope, receive=receive, send=send)

0 commit comments

Comments
 (0)