I have created a testmain.py and that has the following code:
<code>from starlette.responses import StreamingResponse
import asyncio
from fastapi import FastAPI
import json
app = FastAPI()
async def generator():
for i in range(10):
yield json.dumps({"eid":i,"data":f"{i+1}data chunk","is_final_event":i ==9}) + 'n'
await asyncio.sleep(1)
@app.get("/")
def root():
return StreamingResponse(generator(),media_type="application/x-ndjson")
</code>
<code>from starlette.responses import StreamingResponse
import asyncio
from fastapi import FastAPI
import json
app = FastAPI()
async def generator():
for i in range(10):
yield json.dumps({"eid":i,"data":f"{i+1}data chunk","is_final_event":i ==9}) + 'n'
await asyncio.sleep(1)
@app.get("/")
def root():
return StreamingResponse(generator(),media_type="application/x-ndjson")
</code>
from starlette.responses import StreamingResponse
import asyncio
from fastapi import FastAPI
import json
app = FastAPI()
async def generator():
for i in range(10):
yield json.dumps({"eid":i,"data":f"{i+1}data chunk","is_final_event":i ==9}) + 'n'
await asyncio.sleep(1)
@app.get("/")
def root():
return StreamingResponse(generator(),media_type="application/x-ndjson")
When I run the swagger to test the response from http://127.0.0.1:8000/, I get the final response in one-GO and not in real-time (streaming-mode) as and when the yield is executed. It is all responded at once after completion of execution in 10 seconds. How to change this so that it gets responded in real-time. I tried with postman to check the request url but same behavior. It doesn’t give streaming response as the execution happens. Please advise