Skip to content

Commit

Permalink
Allow returning memoryview in StreamingResponse (#2576)
Browse files Browse the repository at this point in the history
  • Loading branch information
bschoenmaeckers committed Apr 22, 2024
1 parent 96c90f2 commit 9fd3ecc
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
4 changes: 2 additions & 2 deletions starlette/responses.py
Expand Up @@ -207,7 +207,7 @@ def __init__(
self.headers["location"] = quote(str(url), safe=":/%#?=@[]!$&'()*+,;")


Content = typing.Union[str, bytes]
Content = typing.Union[str, bytes, memoryview]
SyncContentStream = typing.Iterable[Content]
AsyncContentStream = typing.AsyncIterable[Content]
ContentStream = typing.Union[AsyncContentStream, SyncContentStream]
Expand Down Expand Up @@ -248,7 +248,7 @@ async def stream_response(self, send: Send) -> None:
}
)
async for chunk in self.body_iterator:
if not isinstance(chunk, bytes):
if not isinstance(chunk, (bytes, memoryview)):
chunk = chunk.encode(self.charset)
await send({"type": "http.response.body", "body": chunk, "more_body": True})

Expand Down
7 changes: 7 additions & 0 deletions tests/test_responses.py
Expand Up @@ -541,6 +541,13 @@ def test_streaming_response_known_size(test_client_factory: TestClientFactory) -
assert response.headers["content-length"] == "10"


def test_streaming_response_memoryview(test_client_factory: TestClientFactory) -> None:
app = StreamingResponse(content=iter([memoryview(b"hello"), memoryview(b"world")]))
client: TestClient = test_client_factory(app)
response = client.get("/")
assert response.text == "helloworld"


@pytest.mark.anyio
async def test_streaming_response_stops_if_receiving_http_disconnect() -> None:
streamed = 0
Expand Down

0 comments on commit 9fd3ecc

Please sign in to comment.