Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow use of memoryview with Response #2577

Merged
merged 2 commits into from
Jun 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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