From d1b38037e71a1790a1a8bc55c6e7dfb95d69c5bc Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Sat, 1 Jun 2024 15:12:34 +0200 Subject: [PATCH] Allow use of `memoryview` with `Response` (#2577) --- 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 047ff956..a6975747 100644 --- a/starlette/responses.py +++ b/starlette/responses.py @@ -41,10 +41,10 @@ class Response: 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 fa3c1009..434cc5a2 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 -- 2.47.3