@@ -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
0 commit comments