]> git.ipfire.org Git - thirdparty/starlette.git/commitdiff
Allow use of `memoryview` with `Response` (#2577)
authorAdrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>
Sat, 1 Jun 2024 13:12:34 +0000 (15:12 +0200)
committerGitHub <noreply@github.com>
Sat, 1 Jun 2024 13:12:34 +0000 (13:12 +0000)
starlette/responses.py
tests/test_responses.py

index 047ff9561f45b817bbd18a3c515b05870b1bbb87..a6975747b6d435a71f10f54b181c83ff5df34bf9 100644 (file)
@@ -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
 
index fa3c1009fcc50ecbda32227df5ea6713c07dece2..434cc5a22598a00797d7de9409d7be4e53f9e10a 100644 (file)
@@ -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