@@ -157,6 +157,15 @@ def _check_if_not_already_sent(self) -> None:
157157 if self ._response_already_sent :
158158 raise ResponseAlreadySentError
159159
160+ def _check_chunked (self , expected_value : bool , / ) -> None :
161+ """Prevents calling incompatible methods on chunked/non-chunked response."""
162+ if self .chunked != expected_value :
163+ raise RuntimeError (
164+ "Trying to send non-chunked data in chunked response."
165+ if self .chunked
166+ else "Trying to send chunked data in non-chunked response."
167+ )
168+
160169 def send (
161170 self ,
162171 body : str = "" ,
@@ -169,6 +178,7 @@ def send(
169178 Should be called **only once** per response.
170179 """
171180 self ._check_if_not_already_sent ()
181+ self ._check_chunked (False )
172182
173183 if getattr (body , "encode" , None ):
174184 encoded_response_message_body = body .encode ("utf-8" )
@@ -239,6 +249,7 @@ def send_file( # pylint: disable=too-many-arguments
239249 Should be called **only once** per response.
240250 """
241251 self ._check_if_not_already_sent ()
252+ self ._check_chunked (False )
242253
243254 if safe :
244255 self ._check_file_path_is_valid (filename )
@@ -268,6 +279,8 @@ def send_chunk(self, chunk: str = "") -> None:
268279
269280 :param str chunk: String data to be sent.
270281 """
282+ self ._check_chunked (True )
283+
271284 if getattr (chunk , "encode" , None ):
272285 chunk = chunk .encode ("utf-8" )
273286
0 commit comments