Skip to content
Myr

Add Client.stream() method. (#600)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Add Client.stream() method. * Add top-level stream API * Documentation

authored by Tom Christie · committed by GitHub · parent 38a9d77 · Browse files · 9 files+213 added−34 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+213 added−34 removed

  • tests:+41 added−26 removed
  • other:+172 added−8 removed

9 files+213 added−34 removed

modified:docs/compatibility.md+3 added-4 removed
modified:docs/quickstart.md+48 added-2 removed
290 unmodified lines
291>>> r.headers.get('content-type')292'application/json'293```294295Multiple values for a single response header are represented as a single comma-separated296value, as per [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2):295Multiple values for a single response header are represented as a single comma-separated value, as per [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2):296297> A recipient MAY combine multiple header fields with the same field name into one “field-name: field-value” pair, without changing the semantics of the message, by appending each subsequent field-value to the combined field value in order, separated by a comma.298299## Streaming Responses300301For large downloads you may want to use streaming responses that do not load the entire response body into memory at once.302303You can stream the binary content of the response...304305```306>>> async with httpx.stream("GET", "https://www.example.com") as r:307... async for data in r.stream_bytes():308... print(data)309```310311Or the text of the response...312313```314>>> async with httpx.stream("GET", "https://www.example.com") as r:315... async for text in r.stream_text():316... print(text)317```318319Or stream the text, on a line-by-line basis...320321```322>>> async with httpx.stream("GET", "https://www.example.com") as r:323... async for line in r.stream_lines():324... print(line)325```326327HTTPX will use universal line endings, normalising all cases to `\n`.328329In some cases you might want to access the raw bytes on the response without applying any HTTP content decoding. In this case any content encoding that the web server has applied such as `gzip`, `deflate`, or `brotli` will not be automatically decoded.330331```332>>> async with httpx.stream("GET", "https://www.example.com") as r:333... async for chunk in r.stream_raw():334... print(chunk)335```336337If you're using streaming responses in any of these ways then the `response.content` and `response.text` attributes will not be available, and will raise errors if accessed. However you can also use the response streaming functionality to conditionally load the response body:338339```340>>> async with httpx.stream("GET", "https://www.example.com") as r:341... if r.headers['Content-Length'] < TOO_LONG:342... await r.read()343... print(r.text)344```345346## Cookies347348Any cookies that are set on the response can be easily accessed:349
110 unmodified lines
modified:httpx/__init__.py+2 added-1 removed
1from .__version__ import __description__, __title__, __version__2from .api import delete, get, head, options, patch, post, put, request2from .api import delete, get, head, options, patch, post, put, request, stream3from .auth import BasicAuth, DigestAuth4from .client import Client5from .concurrency.asyncio import AsyncioBackend6from .concurrency.base import (
67 unmodified lines
74 "post",75 "patch",76 "put",77 "request",78 "stream",79 "BasicAuth",80 "Client",81 "DigestAuth",82 "AsyncioBackend",
54 unmodified lines
modified:httpx/api.py+40 added-1 removed
1import typing23from .client import Client3from .client import Client, StreamContextManager4from .config import DEFAULT_TIMEOUT_CONFIG, CertTypes, TimeoutTypes, VerifyTypes5from .models import (6 AuthTypes,7 CookieTypes,8 HeaderTypes,9 QueryParamTypes,10 Request,11 RequestData,12 RequestFiles,13 Response,14 URLTypes,
83 unmodified lines
98 allow_redirects=allow_redirects,99 )100101102def stream(103 method: str,104 url: URLTypes,105 *,106 params: QueryParamTypes = None,107 data: RequestData = None,108 files: RequestFiles = None,109 json: typing.Any = None,110 headers: HeaderTypes = None,111 cookies: CookieTypes = None,112 auth: AuthTypes = None,113 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,114 allow_redirects: bool = True,115 verify: VerifyTypes = True,116 cert: CertTypes = None,117 trust_env: bool = True,118) -> StreamContextManager:119 client = Client(cert=cert, verify=verify, trust_env=trust_env)120 request = Request(121 method=method,122 url=url,123 params=params,124 data=data,125 files=files,126 json=json,127 headers=headers,128 cookies=cookies,129 )130 return StreamContextManager(131 client=client,132 request=request,133 auth=auth,134 timeout=timeout,135 allow_redirects=allow_redirects,136 close_client=True,137 )138139140async def get(141 url: URLTypes,142 *,143 params: QueryParamTypes = None,
271 unmodified lines
modified:httpx/client.py+79 added
1import functools2import typing3import warnings4from types import TracebackType56import hstspreload7
214 unmodified lines
222 verify: VerifyTypes = None,223 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,224 trust_env: bool = None,225 ) -> Response:226 if stream:227 warnings.warn(228 "The 'stream=True' argument is due to be deprecated. "229 "Use 'async with client.stream(method, url, ...) as response' instead."230 )231232 request = self.build_request(233 method=method,234 url=url,235 data=data,
14 unmodified lines
250 trust_env=trust_env,251 )252 return response253254 def stream(255 self,256 method: str,257 url: URLTypes,258 *,259 data: RequestData = None,260 files: RequestFiles = None,261 json: typing.Any = None,262 params: QueryParamTypes = None,263 headers: HeaderTypes = None,264 cookies: CookieTypes = None,265 auth: AuthTypes = None,266 allow_redirects: bool = True,267 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,268 ) -> "StreamContextManager":269 request = self.build_request(270 method=method,271 url=url,272 data=data,273 files=files,274 json=json,275 params=params,276 headers=headers,277 cookies=cookies,278 )279 return StreamContextManager(280 client=self,281 request=request,282 auth=auth,283 allow_redirects=allow_redirects,284 timeout=timeout,285 )286287 def build_request(288 self,289 method: str,290 url: URLTypes,
612 unmodified lines
903 new_proxies[str(key)] = _proxy_from_url(dispatcher_or_url)904 else:905 new_proxies[str(key)] = dispatcher_or_url906 return new_proxies907908909class StreamContextManager:910 def __init__(911 self,912 client: Client,913 request: Request,914 *,915 auth: AuthTypes = None,916 allow_redirects: bool = True,917 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,918 close_client: bool = False,919 ) -> None:920 self.client = client921 self.request = request922 self.auth = auth923 self.allow_redirects = allow_redirects924 self.timeout = timeout925 self.close_client = close_client926927 async def __aenter__(self) -> "Response":928 self.response = await self.client.send(929 request=self.request,930 auth=self.auth,931 allow_redirects=self.allow_redirects,932 timeout=self.timeout,933 stream=True,934 )935 return self.response936937 async def __aexit__(938 self,939 exc_type: typing.Type[BaseException] = None,940 exc_value: BaseException = None,941 traceback: TracebackType = None,942 ) -> None:943 await self.response.close()944 if self.close_client:945 await self.client.close()
modified:tests/client/test_async_client.py+6 added-3 removed
60 unmodified lines
616263async def test_stream_response(server, backend):64 async with httpx.Client(backend=backend) as client:65 response = await client.request("GET", server.url, stream=True)65 async with client.stream("GET", server.url) as response:66 body = await response.read()6768 assert response.status_code == 20067 body = await response.read()69 assert body == b"Hello, world!"70 assert response.content == b"Hello, world!"717273async def test_access_content_stream_response(server, backend):74 async with httpx.Client(backend=backend) as client:74 response = await client.request("GET", server.url, stream=True)75 async with client.stream("GET", server.url) as response:76 pass7778 assert response.status_code == 20079 with pytest.raises(httpx.ResponseNotRead):80 response.content81
81 unmodified lines
modified:tests/client/test_client.py+21 added-17 removed
57 unmodified lines
5859@pytest.mark.asyncio60async def test_stream_response(server):61 async with httpx.Client() as client:62 response = await client.get(server.url, stream=True)62 async with client.stream("GET", server.url) as response:63 content = await response.read()64 assert response.status_code == 20064 content = await response.read()65 assert content == b"Hello, world!"666768@pytest.mark.asyncio69async def test_stream_iterator(server):70 body = b""7172 async with httpx.Client() as client:71 response = await client.get(server.url, stream=True)73 async with client.stream("GET", server.url) as response:74 async for chunk in response.stream_bytes():75 body += chunk7677 assert response.status_code == 20073 body = b""74 async for chunk in response.stream_bytes():75 body += chunk78 assert body == b"Hello, world!"798081@pytest.mark.asyncio82async def test_raw_iterator(server):83 body = b""8485 async with httpx.Client() as client:82 response = await client.get(server.url, stream=True)86 async with client.stream("GET", server.url) as response:87 async for chunk in response.stream_raw():88 body += chunk8990 assert response.status_code == 20084 body = b""85 async for chunk in response.stream_raw():86 body += chunk91 assert body == b"Hello, world!"88 await response.close()929394@pytest.mark.asyncio95async def test_raise_for_status(server):
80 unmodified lines
176177178@pytest.mark.asyncio179async def test_elapsed_delay(server):180 url = server.url.copy_with(path="/slow_response/100")181 async with httpx.Client() as client:178 response = await client.get(server.url.copy_with(path="/slow_response/100"))182 response = await client.get(url)183 assert response.elapsed.total_seconds() == pytest.approx(0.1, rel=0.2)184185186@pytest.mark.asyncio187async def test_elapsed_delay_ignores_read_time(server):188 url = server.url.copy_with(path="/slow_response/100")189 async with httpx.Client() as client:185 response = await client.get(186 server.url.copy_with(path="/slow_response/100"), stream=True187 )188 sleep(0.2)189 await response.read()190 async with client.stream("GET", url) as response:191 sleep(0.2)192 await response.read()193194 assert response.elapsed.total_seconds() == pytest.approx(0.1, rel=0.2)
modified:tests/test_api.py+11 added
65 unmodified lines
66 assert response.reason_phrase == "OK"676869@pytest.mark.asyncio70async def test_stream(server):71 async with httpx.stream("GET", server.url) as response:72 await response.read()7374 assert response.status_code == 20075 assert response.reason_phrase == "OK"76 assert response.text == "Hello, world!"77 assert response.http_version == "HTTP/1.1"787980@pytest.mark.asyncio81async def test_get_invalid_url(server):82 with pytest.raises(httpx.InvalidURL):83 await httpx.get("invalid://example.org")
modified:tests/test_timeouts.py+3 added-6 removed
42 unmodified lines
4344 async with Client(45 pool_limits=pool_limits, timeout=timeout, backend=backend46 ) as client:47 response = await client.get(server.url, stream=True)4849 with pytest.raises(PoolTimeout):50 await client.get("http://localhost:8000/")47 async with client.stream("GET", server.url):48 with pytest.raises(PoolTimeout):49 await client.get("http://localhost:8000/")5152 await response.read()