Skip to content

Commit

Permalink
Allow use of memoryview with Response (encode#2577)
Browse files Browse the repository at this point in the history
  • Loading branch information
adriangb authored and Rocky Allen committed Jul 20, 2024
1 parent c61419e commit 3f2bb6e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
4 changes: 2 additions & 2 deletions starlette/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
11 changes: 9 additions & 2 deletions tests/test_responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 3f2bb6e

Please sign in to comment.