Avoid special handling of StreamingHTTPResponse.

This commit is contained in:
L. Kärkkäinen 2020-03-08 17:46:31 +02:00
parent 5351cda979
commit c86c29e239
2 changed files with 12 additions and 10 deletions

View File

@ -22,7 +22,7 @@ from sanic.constants import HTTP_METHODS
from sanic.exceptions import SanicException, ServerError, URLBuildError from sanic.exceptions import SanicException, ServerError, URLBuildError
from sanic.handlers import ErrorHandler from sanic.handlers import ErrorHandler
from sanic.log import LOGGING_CONFIG_DEFAULTS, error_logger, logger from sanic.log import LOGGING_CONFIG_DEFAULTS, error_logger, logger
from sanic.response import HTTPResponse, StreamingHTTPResponse from sanic.response import BaseHTTPResponse, HTTPResponse
from sanic.router import Router from sanic.router import Router
from sanic.server import ( from sanic.server import (
AsyncioServer, AsyncioServer,
@ -1049,10 +1049,8 @@ class Sanic:
"Exception occurred in one of response " "Exception occurred in one of response "
"middleware handlers" "middleware handlers"
) )
# Stream response # Make sure that response is finished / run StreamingHTTP callback
if isinstance(response, StreamingHTTPResponse): if isinstance(response, BaseHTTPResponse):
await response.stream(request)
elif isinstance(response, HTTPResponse):
await request.respond(response).send(end_stream=True) await request.respond(response).send(end_stream=True)
else: else:
raise ServerError( raise ServerError(

View File

@ -77,6 +77,8 @@ class BaseHTTPResponse:
class StreamingHTTPResponse(BaseHTTPResponse): class StreamingHTTPResponse(BaseHTTPResponse):
"""Old style streaming response. Use `request.respond()` instead of this in
new code to avoid the callback."""
__slots__ = ( __slots__ = (
"protocol", "protocol",
"streaming_fn", "streaming_fn",
@ -105,12 +107,14 @@ class StreamingHTTPResponse(BaseHTTPResponse):
:param data: str or bytes-ish data to be written. :param data: str or bytes-ish data to be written.
""" """
await self.send(self._encode_body(data)) await super().send(self._encode_body(data))
async def stream(self, request): async def send(self, *args, **kwargs):
request.respond(self) if self.streaming_fn is not None:
await self.streaming_fn(self) await self.streaming_fn(self)
await self.send(end_stream=True) self.streaming_fn = None
await super().send(*args, **kwargs)
class HTTPResponse(BaseHTTPResponse): class HTTPResponse(BaseHTTPResponse):