@@ -98,6 +98,7 @@ def __init__( # pylint: disable=too-many-arguments
98
98
self .content_type = content_type
99
99
self .http_version = http_version
100
100
self .chunked = chunked
101
+ self ._response_already_sent = False
101
102
102
103
def _send_headers (
103
104
self ,
@@ -141,13 +142,17 @@ def send(
141
142
142
143
Should be called **only once** per response.
143
144
"""
145
+ if self ._response_already_sent :
146
+ raise RuntimeError ("Response was already sent" )
147
+
144
148
encoded_response_message_body = body .encode ("utf-8" )
145
149
146
150
self ._send_headers (
147
151
content_type = content_type or self .content_type ,
148
152
content_length = len (encoded_response_message_body ),
149
153
)
150
154
self ._send_bytes (self .request .connection , encoded_response_message_body )
155
+ self ._response_already_sent = True
151
156
152
157
def send_file (
153
158
self ,
@@ -160,6 +165,9 @@ def send_file(
160
165
161
166
Should be called **only once** per response.
162
167
"""
168
+ if self ._response_already_sent :
169
+ raise RuntimeError ("Response was already sent" )
170
+
163
171
if not root_path .endswith ("/" ):
164
172
root_path += "/"
165
173
try :
@@ -177,6 +185,7 @@ def send_file(
177
185
with open (root_path + filename , "rb" ) as file :
178
186
while bytes_read := file .read (2048 ):
179
187
self ._send_bytes (self .request .connection , bytes_read )
188
+ self ._response_already_sent = True
180
189
181
190
def send_chunk (self , chunk : str = "" ) -> None :
182
191
"""
@@ -198,7 +207,10 @@ def __enter__(self):
198
207
self ._send_headers ()
199
208
return self
200
209
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
+
202
214
if self .chunked :
203
215
self .send_chunk ("" )
204
216
return True
0 commit comments