response.write should be synchronous for performance reasons

This commit is contained in:
Suby Raman 2017-02-22 10:42:16 -05:00
parent 1a8961587c
commit d8a6d7e02f
3 changed files with 10 additions and 8 deletions

View File

@ -11,8 +11,8 @@ app = Sanic(__name__)
@app.route("/") @app.route("/")
async def test(request): async def test(request):
async def sample_streaming_fn(response): async def sample_streaming_fn(response):
await response.write('foo,') response.write('foo,')
await response.write('bar') response.write('bar')
return stream(sample_streaming_fn, content_type='text/csv') return stream(sample_streaming_fn, content_type='text/csv')
``` ```
@ -26,7 +26,7 @@ async def index(request):
conn = await asyncpg.connect(database='test') conn = await asyncpg.connect(database='test')
async with conn.transaction(): async with conn.transaction():
async for record in conn.cursor('SELECT generate_series(0, 10)'): 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) return stream(stream_from_db)
``` ```

View File

@ -109,19 +109,21 @@ class StreamingHTTPResponse(BaseHTTPResponse):
'status', 'content_type', 'headers', '_cookies') 'status', 'content_type', 'headers', '_cookies')
def __init__(self, streaming_fn, status=200, headers=None, 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.content_type = content_type
self.streaming_fn = streaming_fn self.streaming_fn = streaming_fn
self.status = status self.status = status
self.headers = headers or {} self.headers = headers or {}
self._cookies = None self._cookies = None
async def write(self, data): def write(self, data):
"""Writes a chunk of data to the streaming response. """Writes a chunk of data to the streaming response.
:param data: bytes-ish data to be written. :param data: bytes-ish data to be written.
""" """
if type(data) != bytes:
data = self._encode_body(data) data = self._encode_body(data)
self.transport.write( self.transport.write(
b"%b\r\n%b\r\n" % (str(len(data)).encode(), data)) b"%b\r\n%b\r\n" % (str(len(data)).encode(), data))

View File

@ -22,9 +22,9 @@ def test_response_body_not_a_string():
async def sample_streaming_fn(response): async def sample_streaming_fn(response):
await response.write('foo,') response.write('foo,')
await asyncio.sleep(.001) await asyncio.sleep(.001)
await response.write('bar') response.write('bar')
@pytest.fixture @pytest.fixture