From df358751ccf53ca936739c38e3bc3eebf46b5357 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Mon, 22 Apr 2024 12:26:01 -0500 Subject: [PATCH] Allow use of memoryview with Response --- starlette/responses.py | 4 ++-- tests/test_responses.py | 11 +++++++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/starlette/responses.py b/starlette/responses.py index 047ff9561..a6975747b 100644 --- a/starlette/responses.py +++ b/starlette/responses.py @@ -41,10 +41,10 @@ def __init__( self.body = self.render(content) self.init_headers(headers) - def render(self, content: typing.Any) -> bytes: + def render(self, content: typing.Any) -> bytes | memoryview: if content is None: return b"" - if isinstance(content, bytes): + if isinstance(content, (bytes, memoryview)): return content return content.encode(self.charset) # type: ignore diff --git a/tests/test_responses.py b/tests/test_responses.py index fa3c1009f..434cc5a22 100644 --- a/tests/test_responses.py +++ b/tests/test_responses.py @@ -541,11 +541,18 @@ def test_streaming_response_known_size(test_client_factory: TestClientFactory) - assert response.headers["content-length"] == "10" +def test_response_memoryview(test_client_factory: TestClientFactory) -> None: + app = Response(content=memoryview(b"\xC0")) + client: TestClient = test_client_factory(app) + response = client.get("/") + assert response.content == b"\xC0" + + def test_streaming_response_memoryview(test_client_factory: TestClientFactory) -> None: - app = StreamingResponse(content=iter([memoryview(b"hello"), memoryview(b"world")])) + app = StreamingResponse(content=iter([memoryview(b"\xC0"), memoryview(b"\xF5")])) client: TestClient = test_client_factory(app) response = client.get("/") - assert response.text == "helloworld" + assert response.content == b"\xC0\xF5" @pytest.mark.anyio