diff --git a/docs/sanic/streaming.md b/docs/sanic/streaming.md index b215c6ab..c13fffb3 100644 --- a/docs/sanic/streaming.md +++ b/docs/sanic/streaming.md @@ -11,8 +11,8 @@ app = Sanic(__name__) @app.route("/") async def test(request): async def sample_streaming_fn(response): - await response.write('foo,') - await response.write('bar') + response.write('foo,') + response.write('bar') return stream(sample_streaming_fn, content_type='text/csv') ``` @@ -26,7 +26,7 @@ async def index(request): conn = await asyncpg.connect(database='test') async with conn.transaction(): async for record in conn.cursor('SELECT generate_series(0, 10)'): - await response.write(record[0]) + response.write(record[0]) return stream(stream_from_db) ``` \ No newline at end of file diff --git a/sanic/response.py b/sanic/response.py index d11bd6c7..c36c0181 100644 --- a/sanic/response.py +++ b/sanic/response.py @@ -109,19 +109,21 @@ class StreamingHTTPResponse(BaseHTTPResponse): 'status', 'content_type', 'headers', '_cookies') def __init__(self, streaming_fn, status=200, headers=None, - content_type='text/plain', body_bytes=b''): + content_type='text/plain'): self.content_type = content_type self.streaming_fn = streaming_fn self.status = status self.headers = headers or {} self._cookies = None - async def write(self, data): + def write(self, data): """Writes a chunk of data to the streaming response. :param data: bytes-ish data to be written. """ - data = self._encode_body(data) + if type(data) != bytes: + data = self._encode_body(data) + self.transport.write( b"%b\r\n%b\r\n" % (str(len(data)).encode(), data)) diff --git a/tests/test_response.py b/tests/test_response.py index 13635e5e..ff5fd42b 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -22,9 +22,9 @@ def test_response_body_not_a_string(): async def sample_streaming_fn(response): - await response.write('foo,') + response.write('foo,') await asyncio.sleep(.001) - await response.write('bar') + response.write('bar') @pytest.fixture