]> git.ipfire.org Git - thirdparty/httpx.git/commitdiff
Add "manual streaming mode" docs (#1046)
authorFlorimond Manca <florimond.manca@gmail.com>
Tue, 7 Jul 2020 12:37:12 +0000 (14:37 +0200)
committerGitHub <noreply@github.com>
Tue, 7 Jul 2020 12:37:12 +0000 (14:37 +0200)
Co-authored-by: Tom Christie <tom@tomchristie.com>
docs/async.md

index b56f04197143160d760d224672f70735f85e2508..a6a3c06bfe393b471ef7931a0cf74d8dccb18058 100644 (file)
@@ -78,7 +78,27 @@ The async response streaming methods are:
 * `Response.aiter_text()` - For streaming the response content as text.
 * `Response.aiter_lines()` - For streaming the response content as lines of text.
 * `Response.aiter_raw()` - For streaming the raw response bytes, without applying content decoding.
-* `Response.aclose()` - For closing the response. You don't usually need this, since `.stream` block close the response automatically on exit.
+* `Response.aclose()` - For closing the response. You don't usually need this, since `.stream` block closes the response automatically on exit.
+
+For situations when context block usage is not practical, it is possible to enter "manual mode" by sending a [`Request` instance](./advanced.md#request-instances) using `client.send(..., stream=True)`.
+
+Example in the context of forwarding the response to a streaming web endpoint with [Starlette](https://www.starlette.io):
+
+```python
+import httpx
+from starlette.background import BackgroundTask
+from starlette.responses import StreamingResponse
+
+client = httpx.AsyncClient()
+
+async def home(request):
+    req = client.build_request("GET", "https://www.example.com/")
+    r = await client.send(req, stream=True)
+    return StreamingResponse(r.aiter_text(), background=BackgroundTask(r.aclose))
+```
+
+!!! warning
+    When using this "manual streaming mode", it is your duty as a developer to make sure that `Response.aclose()` is called eventually. Failing to do so would leave connections open, most likely resulting in resource leaks down the line.
 
 ### Streaming requests