21
21
BackslashInPathError ,
22
22
FileNotExistsError ,
23
23
ParentDirectoryReferenceError ,
24
- ResponseAlreadySentException ,
24
+ ResponseAlreadySentError ,
25
25
)
26
26
from .mime_type import MIMEType
27
27
from .request import HTTPRequest
@@ -147,6 +147,21 @@ def _send_headers(
147
147
self .request .connection , response_message_header .encode ("utf-8" )
148
148
)
149
149
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
150
165
def send (
151
166
self ,
152
167
body : str = "" ,
@@ -158,8 +173,6 @@ def send(
158
173
159
174
Should be called **only once** per response.
160
175
"""
161
- if self ._response_already_sent :
162
- raise ResponseAlreadySentException
163
176
164
177
if getattr (body , "encode" , None ):
165
178
encoded_response_message_body = body .encode ("utf-8" )
@@ -200,6 +213,7 @@ def _get_file_length(file_path: str) -> int:
200
213
except OSError :
201
214
raise FileNotExistsError (file_path ) # pylint: disable=raise-missing-from
202
215
216
+ @_prevent_multiple_send_calls
203
217
def send_file (
204
218
self ,
205
219
filename : str = "index.html" ,
@@ -214,8 +228,6 @@ def send_file(
214
228
215
229
Should be called **only once** per response.
216
230
"""
217
- if self ._response_already_sent :
218
- raise ResponseAlreadySentException
219
231
220
232
if safe :
221
233
self ._check_file_path_is_valid (filename )
0 commit comments