@@ -1222,6 +1222,10 @@ def flush(self, include_footers: bool = False) -> "Future[None]":
1222
1222
future .set_result (None )
1223
1223
return future
1224
1224
1225
+ def _should_not_send_content (self , status_code : int ) -> bool :
1226
+ """Check if we should not send body content for given `status_code`"""
1227
+ return status_code in (204 , 304 ) or (100 <= status_code < 200 )
1228
+
1225
1229
def finish (self , chunk : Optional [Union [str , bytes , dict ]] = None ) -> "Future[None]" :
1226
1230
"""Finishes this response, ending the HTTP request.
1227
1231
@@ -1255,10 +1259,9 @@ def finish(self, chunk: Optional[Union[str, bytes, dict]] = None) -> "Future[Non
1255
1259
if self .check_etag_header ():
1256
1260
self ._write_buffer = []
1257
1261
self .set_status (304 )
1258
- if self ._status_code in (204 , 304 ) or (100 <= self ._status_code < 200 ):
1259
- assert not self ._write_buffer , (
1260
- "Cannot send body with %s" % self ._status_code
1261
- )
1262
+ if self ._should_not_send_content (self ._status_code ):
1263
+ if self ._write_buffer :
1264
+ raise RuntimeError (f"Cannot send body with status code HTTP{ self ._status_code } " )
1262
1265
self ._clear_representation_headers ()
1263
1266
elif "Content-Length" not in self ._headers :
1264
1267
content_length = sum (len (part ) for part in self ._write_buffer )
@@ -1349,7 +1352,9 @@ def write_error(self, status_code: int, **kwargs: Any) -> None:
1349
1352
the "current" exception for purposes of methods like
1350
1353
``sys.exc_info()`` or ``traceback.format_exc``.
1351
1354
"""
1352
- if self .settings .get ("serve_traceback" ) and "exc_info" in kwargs :
1355
+ if self ._should_not_send_content (status_code ):
1356
+ self .finish ()
1357
+ elif self .settings .get ("serve_traceback" ) and "exc_info" in kwargs :
1353
1358
# in debug mode, try to send a traceback
1354
1359
self .set_header ("Content-Type" , "text/plain" )
1355
1360
for line in traceback .format_exception (* kwargs ["exc_info" ]):
0 commit comments