Skip to content

Commit 20f50ac

Browse files
committed
Allow sending raw bytes in the response
We now only encode the body if it has an encode method, which usually means it's a string. This allows passing bytes, bytearray or memoryview. I also changed the logic for sending a chunk, that avoids copying the data unnecessarily. I believe this also fixes a bug, where the size of unencoded chunk was sent, in characters, instead of encoded size, in bytes.
1 parent e4a7e0e commit 20f50ac

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

adafruit_httpserver/response.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,10 @@ def send(
155155
if self._response_already_sent:
156156
raise RuntimeError("Response was already sent")
157157

158-
encoded_response_message_body = body.encode("utf-8")
158+
if getattr(body, "encode", None):
159+
encoded_response_message_body = body.encode("utf-8")
160+
else:
161+
encoded_response_message_body = body
159162

160163
self._send_headers(
161164
content_type=content_type or self.content_type,
@@ -206,11 +209,12 @@ def send_chunk(self, chunk: str = "") -> None:
206209
207210
:param str chunk: String data to be sent.
208211
"""
209-
hex_length = hex(len(chunk))[2:] # removing 0x
212+
if getattr(chunk, "encode", None):
213+
chunk = chunk.encode("utf-8")
210214

211-
self._send_bytes(
212-
self.request.connection, f"{hex_length}\r\n{chunk}\r\n".encode("utf-8")
213-
)
215+
self._send_bytes(self.request.connection, b"%x\r\n" % len(chunk))
216+
self._send_bytes(self.request.connection, chunk)
217+
self._send_bytes(self.request.connection, b"\r\n")
214218

215219
def __enter__(self):
216220
if self.chunked:

0 commit comments

Comments
 (0)