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