Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch to request context manager interface #1355

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/advanced.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,8 @@ To dispatch a `Request` instance across to the network, create a [`Client` insta

```python
with httpx.Client() as client:
response = client.send(request)
with client.send(request) as response:
response.read()
...
```

Expand Down
6 changes: 5 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,11 @@ what gets sent over the wire.*

```pycon
>>> request = httpx.Request("GET", "https://example.org", headers={'host': 'example.org'})
>>> response = client.send(request)
>>> with client.send(request) as response:
... response.read()
...
>>> response.status_code
200
```

* `def __init__(method, url, [params], [headers], [cookies], [content], [data], [files], [json], [stream])`
Expand Down
18 changes: 13 additions & 5 deletions docs/async.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,12 @@ The async response streaming methods are:
* `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 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)`.
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(...)`.

Example in the context of forwarding the response to a streaming web endpoint with [Starlette](https://www.starlette.io):

```python
import contextlib
import httpx
from starlette.background import BackgroundTask
from starlette.responses import StreamingResponse
Expand All @@ -94,12 +95,19 @@ 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))
exit_stack = contextlib.AsyncExitStack()
r = await exit_stack.enter_async_context(client.send(req))
return StreamingResponse(r.aiter_text(), background=BackgroundTask(exit_stack.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.
**Note**: When using this "manual streaming mode", it is your duty as a developer to make sure that the response is eventually properly closed. Failing to do so would leave connections open, most likely resulting in resource leaks down the line. In the above example, we use an `AsyncExitStack` to properly enter and then clean up the context manager returned by `client.send()`. This approach is the least error-prone. Alternatively, you could enter the context manually, and call `.aclose()` on the response:

```python
async def home(request):
req = client.build_request("GET", "https://www.example.com/")
r = await client.send(req).__aenter__()
return StreamingResponse(r.aiter_text(), background=BackgroundTask(r.aclose))
```

### Streaming requests

Expand Down
46 changes: 23 additions & 23 deletions httpx/_api.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import typing
from contextlib import contextmanager

from ._client import Client, StreamContextManager
from ._client import Client
from ._config import DEFAULT_TIMEOUT_CONFIG
from ._models import Request, Response
from ._models import Response
from ._types import (
AuthTypes,
CertTypes,
Expand Down Expand Up @@ -105,6 +106,7 @@ def request(
)


@contextmanager
def stream(
method: str,
url: URLTypes,
Expand All @@ -123,7 +125,7 @@ def stream(
verify: VerifyTypes = True,
cert: CertTypes = None,
trust_env: bool = True,
) -> StreamContextManager:
) -> typing.Iterator[Response]:
"""
Alternative to `httpx.request()` that streams the response body
instead of loading it into memory at once.
Expand All @@ -134,26 +136,24 @@ def stream(

[0]: /quickstart#streaming-responses
"""
client = Client(proxies=proxies, cert=cert, verify=verify, trust_env=trust_env)
request = Request(
method=method,
url=url,
params=params,
content=content,
data=data,
files=files,
json=json,
headers=headers,
cookies=cookies,
)
return StreamContextManager(
client=client,
request=request,
auth=auth,
timeout=timeout,
allow_redirects=allow_redirects,
close_client=True,
)
with Client(
proxies=proxies, cert=cert, verify=verify, trust_env=trust_env
) as client:
with client.stream(
method=method,
url=url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
allow_redirects=allow_redirects,
timeout=timeout,
) as response:
yield response


def get(
Expand Down
Loading