How clients can get chunks from StreamingResponse
#2365
-
There are excellent docs for servers on However, it doesn't show what a potential client can look like takes advantage of the streaming support. How can a client iterate over chunks coming from a Using import asyncio
import statistics
import time
from starlette.responses import StreamingResponse
from starlette.testclient import TestClient
# SEE: https://www.starlette.io/responses/#streamingresponse
async def slow_numbers(minimum, maximum):
yield "<html><body><ul>"
for number in range(minimum, maximum + 1):
yield "<li>%d</li>" % number
await asyncio.sleep(0.5)
yield "</ul></body></html>"
async def app(scope, receive, send):
assert scope["type"] == "http"
response = StreamingResponse(slow_numbers(1, 5), media_type="text/html")
await response(scope, receive, send)
def test_streaming() -> None:
texts, times = [], []
tic = time.perf_counter()
client = TestClient(app=app)
with client.stream("GET", "/test/streaming") as r:
times.append((toc := time.perf_counter()) - tic)
tic = toc
for text in r.iter_text():
texts.append(text)
times.append((toc := time.perf_counter()) - tic)
tic = toc
assert len(times) > 2, "Should be more than one chunk"
assert statistics.mean(times) < 1, "Should be streaming" |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Okay I have hunted this down somewhat. I believe the issue is in
I believe the bug is in |
Beta Was this translation helpful? Give feedback.
This is a known issue: #1102