Skip to content

Commit 9b9adfc

Browse files
committed
Extracted multiple send calls logic into decorator
1 parent a545ca7 commit 9b9adfc

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed

adafruit_httpserver/exceptions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def __init__(self, path: str) -> None:
3434
super().__init__(f"Backslash in path: {path}")
3535

3636

37-
class ResponseAlreadySentException(Exception):
37+
class ResponseAlreadySentError(Exception):
3838
"""
3939
Another ``HTTPResponse`` has already been sent. There can only be one per ``HTTPRequest``.
4040
"""

adafruit_httpserver/response.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
BackslashInPathError,
2222
FileNotExistsError,
2323
ParentDirectoryReferenceError,
24-
ResponseAlreadySentException,
24+
ResponseAlreadySentError,
2525
)
2626
from .mime_type import MIMEType
2727
from .request import HTTPRequest
@@ -147,6 +147,21 @@ def _send_headers(
147147
self.request.connection, response_message_header.encode("utf-8")
148148
)
149149

150+
def _prevent_multiple_send_calls(function):
151+
"""
152+
Decorator that prevents calling `send` or `send_file` more than once.
153+
"""
154+
155+
def wrapper(self: HTTPResponse, *args, **kwargs):
156+
if self._response_already_sent:
157+
raise ResponseAlreadySentError
158+
159+
result = function(self, *args, **kwargs)
160+
return result
161+
162+
return wrapper
163+
164+
@_prevent_multiple_send_calls
150165
def send(
151166
self,
152167
body: str = "",
@@ -158,8 +173,6 @@ def send(
158173
159174
Should be called **only once** per response.
160175
"""
161-
if self._response_already_sent:
162-
raise ResponseAlreadySentException
163176

164177
if getattr(body, "encode", None):
165178
encoded_response_message_body = body.encode("utf-8")
@@ -200,6 +213,7 @@ def _get_file_length(file_path: str) -> int:
200213
except OSError:
201214
raise FileNotExistsError(file_path) # pylint: disable=raise-missing-from
202215

216+
@_prevent_multiple_send_calls
203217
def send_file(
204218
self,
205219
filename: str = "index.html",
@@ -214,8 +228,6 @@ def send_file(
214228
215229
Should be called **only once** per response.
216230
"""
217-
if self._response_already_sent:
218-
raise ResponseAlreadySentException
219231

220232
if safe:
221233
self._check_file_path_is_valid(filename)

0 commit comments

Comments
 (0)