Skip to content

Commit f0b61a7

Browse files
committed
Prevented from calling .send() multiple times and added deprecation error if handler returns HTTPResponse
1 parent 4b61d74 commit f0b61a7

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

adafruit_httpserver/response.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ def __init__( # pylint: disable=too-many-arguments
9898
self.content_type = content_type
9999
self.http_version = http_version
100100
self.chunked = chunked
101+
self._response_already_sent = False
101102

102103
def _send_headers(
103104
self,
@@ -141,13 +142,17 @@ def send(
141142
142143
Should be called **only once** per response.
143144
"""
145+
if self._response_already_sent:
146+
raise RuntimeError("Response was already sent")
147+
144148
encoded_response_message_body = body.encode("utf-8")
145149

146150
self._send_headers(
147151
content_type=content_type or self.content_type,
148152
content_length=len(encoded_response_message_body),
149153
)
150154
self._send_bytes(self.request.connection, encoded_response_message_body)
155+
self._response_already_sent = True
151156

152157
def send_file(
153158
self,
@@ -160,6 +165,9 @@ def send_file(
160165
161166
Should be called **only once** per response.
162167
"""
168+
if self._response_already_sent:
169+
raise RuntimeError("Response was already sent")
170+
163171
if not root_path.endswith("/"):
164172
root_path += "/"
165173
try:
@@ -177,6 +185,7 @@ def send_file(
177185
with open(root_path + filename, "rb") as file:
178186
while bytes_read := file.read(2048):
179187
self._send_bytes(self.request.connection, bytes_read)
188+
self._response_already_sent = True
180189

181190
def send_chunk(self, chunk: str = "") -> None:
182191
"""
@@ -198,7 +207,10 @@ def __enter__(self):
198207
self._send_headers()
199208
return self
200209

201-
def __exit__(self, *args, **kwargs):
210+
def __exit__(self, exception_type, exception_value, exception_traceback):
211+
if exception_type is not None:
212+
return False
213+
202214
if self.chunked:
203215
self.send_chunk("")
204216
return True

adafruit_httpserver/server.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,12 @@ def poll(self):
160160

161161
# If a handler for route exists and is callable, call it.
162162
if handler is not None and callable(handler):
163-
handler(request)
163+
output = handler(request)
164+
# TODO: Remove this deprecation error in future
165+
if isinstance(output, HTTPResponse):
166+
raise RuntimeError(
167+
"Returning an HTTPResponse from a route handler is deprecated."
168+
)
164169

165170
# If no handler exists and request method is GET, try to serve a file.
166171
elif handler is None and request.method == HTTPMethod.GET:

0 commit comments

Comments
 (0)