What is HTTP Streaming?
HTTP Streaming is a push-style data transfer technique that allows a web server to continuously send data to a client over a single HTTP connection that remains open indefinitely. Technically, this goes against HTTP convention, but HTTP Streaming is an efficient method to transfer all kinds of dynamic or otherwise streamable data between the server and client without reinventing HTTP.
Create streaming API with the aiohttp
You can steam text or data using the web.StreamRespone in aiohttp. also use for reflect changes on real time.
from aiohttp import web
async def hello(request):
stream = web.StreamResponse()
await stream.prepare(request)
for i in range(1, 10):
if stream.task.done() or stream.task.cancelled():
break
await stream.write(bytearray(f'no: {i} ', 'utf-8'))
await asyncio.sleep(1)
await stream.write_eof()
return stream
app = web.Application()
app.add_routes([
web.get('/', handle)
])
web.run_app(app)