From d8a6d7e02f7628ab4b910e31a6860147c3a2134f Mon Sep 17 00:00:00 2001 From: Suby Raman Date: Wed, 22 Feb 2017 10:42:16 -0500 Subject: [PATCH] response.write should be synchronous for performance reasons --- docs/sanic/streaming.md | 6 +++--- sanic/response.py | 8 +++++--- tests/test_response.py | 4 ++-- 3 files changed, 10 insertions(+), 8 deletions(-) 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