Flush StreamResponse in aiohttp.web

16 views Asked by At

I want to periodically send text through an http connection to the browser using aiohttp. In the example below every second I am sending the number of seconds that have elapsed up until a certain time. However, it just waits for n seconds and then sends the entire block of text. I need to be able to flush the connection and send all the data after sending the time elapsed but I can't find how.

Here is the sample code:

import asyncio
from aiohttp import web

routes = web.RouteTableDef()

@routes.get('/sleep/{time}')
async def sleep(request):
    response = web.StreamResponse(
        status=200,
        reason='OK',
        headers={'Content-Type': 'text/plain'},
    )
    await response.prepare(request)
    
    time = float(request.match_info.get('time', 1))
    for i in range(int(time) + 1):
        await response.write(("%d\n" % i).encode("utf-8"))
        if time - i >= 1:
            await asyncio.sleep(1)
    await asyncio.sleep(time % 1)
    await response.write_eof("done".encode('utf-8'))
    
    return response

app = web.Application()
app.add_routes(routes)
web.run_app(app)

I checked that this wasn't a client side issue by adding the line await response.write(("_" * 1024).encode('utf-8')) sending the seconds and it sent more data every second. I also looked through their documentation and couldn't find anything.

I am expecting to only have to send the number every second.

0

There are 0 answers