@@ -157,6 +157,15 @@ def _check_if_not_already_sent(self) -> None:
157
157
if self ._response_already_sent :
158
158
raise ResponseAlreadySentError
159
159
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
+
160
169
def send (
161
170
self ,
162
171
body : str = "" ,
@@ -169,6 +178,7 @@ def send(
169
178
Should be called **only once** per response.
170
179
"""
171
180
self ._check_if_not_already_sent ()
181
+ self ._check_chunked (False )
172
182
173
183
if getattr (body , "encode" , None ):
174
184
encoded_response_message_body = body .encode ("utf-8" )
@@ -239,6 +249,7 @@ def send_file( # pylint: disable=too-many-arguments
239
249
Should be called **only once** per response.
240
250
"""
241
251
self ._check_if_not_already_sent ()
252
+ self ._check_chunked (False )
242
253
243
254
if safe :
244
255
self ._check_file_path_is_valid (filename )
@@ -268,6 +279,8 @@ def send_chunk(self, chunk: str = "") -> None:
268
279
269
280
:param str chunk: String data to be sent.
270
281
"""
282
+ self ._check_chunked (True )
283
+
271
284
if getattr (chunk , "encode" , None ):
272
285
chunk = chunk .encode ("utf-8" )
273
286
0 commit comments