from aiohttp import web import json async def stream_handler(request): resp = web.StreamResponse(status=200, reason='OK', content_type='application/json') await resp.prepare(request) try: for i in range(5): data = {'message': f"Hello World {i}"} await resp.write(json.dumps(data).encode('utf-8')) await resp.write(b'\n') await asyncio.sleep(1) await resp.write_eof() except ConnectionResetError: pass return resp app = web.Application() app.router.add_get('/stream', stream_handler) web.run_app(app, host='localhost', port=8080)
from aiohttp import web async def stream_handler(request): resp = web.StreamResponse(status=200, reason='OK', content_type='text/plain') await resp.prepare(request) try: for i in range(5): data = f"Hello World {i}\n" await resp.write(data.encode('utf-8')) await asyncio.sleep(1) await resp.write_eof() except ConnectionResetError: pass return resp app = web.Application() app.router.add_get('/stream', stream_handler) web.run_app(app, host='localhost', port=8080)In this example, we define a stream handler function that sends a streaming text response back to the client. We use the `StreamResponse` class to create the response object and set the content type to `text/plain`. We then write text data to the response object in a loop with a delay of one second between each write to simulate streaming. Finally, we close the response with `write_eof()`.