File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -701,6 +701,26 @@ Example:
701701 :language: python
702702
703703
704+ Streaming responses
705+ -------------------
706+
707+ To test a streaming client, return a Werkzeug ``Response ``
708+ with an iterable body from a custom request handler. Each value yielded by the
709+ iterable supplies another part of the response body.
710+
711+ This example sends two server-sent events. It waits for the client to read the
712+ first event before producing the second one:
713+
714+ .. literalinclude :: ../tests/examples/test_howto_streaming.py
715+ :language: python
716+
717+ Requests needs ``stream=True `` to read the response incrementally.
718+ ``iter_lines(chunk_size=1) `` keeps its read buffer small enough to deliver the
719+ first event while the producer is waiting. The response context manager closes
720+ the connection, and the ``finally `` block releases the producer if an assertion
721+ fails. The timeouts bound waits when the client or server fails to progress.
722+
723+
704724Serving requests in parallel
705725----------------------------
706726
Original file line number Diff line number Diff line change 1+ from collections .abc import Iterator
2+ from threading import Event
3+
4+ import requests
5+ from werkzeug import Request
6+ from werkzeug import Response
7+
8+ from pytest_httpserver import HTTPServer
9+
10+
11+ def test_streaming_response (httpserver : HTTPServer ) -> None :
12+ release = Event ()
13+ finished = Event ()
14+
15+ def events () -> Iterator [bytes ]:
16+ yield b"data: first\n \n "
17+ assert release .wait (5 ), "The client did not release the second event"
18+ yield b"data: [DONE]\n \n "
19+ finished .set ()
20+
21+ def handler (_request : Request ) -> Response :
22+ return Response (events (), mimetype = "text/event-stream" )
23+
24+ httpserver .expect_request ("/events" ).respond_with_handler (handler )
25+ try :
26+ with requests .get (httpserver .url_for ("/events" ), stream = True , timeout = 10 ) as response :
27+ response .raise_for_status ()
28+ lines = response .iter_lines (chunk_size = 1 )
29+ assert next (lines ) == b"data: first"
30+ assert next (lines ) == b""
31+ assert not finished .is_set ()
32+ release .set ()
33+ assert list (lines ) == [b"data: [DONE]" , b"" ]
34+ finally :
35+ release .set ()
36+ httpserver .check ()
You can’t perform that action at this time.
0 commit comments