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
Provenance
- Commit
8d8ea8b- Tree
d8667ad- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
38a9d77
9 files changed+213 added−34 removed
modified:docs/compatibility.md+3 added-4 removed
8 unmodified lines910111213141513141517161718192018 unmodified lines8 unmodified linesPretty much any API mentioned in the `requests` QuickStart should be identicalto the API in our own documentation. The following exceptions apply:
* `Response.url` - Returns a `URL` instance, rather than a string. Use `str(response.url)` if you need a string instance.* `httpx.codes` - In our documentation we prefer the uppercased versions, such as `codes.NOT_FOUND`,but also provide lower-cased versions for API compatibility with `requests`.* `stream=True`. - Streaming responses provide the `.stream()` and `.raw()` byte iterator interfaces, rather than the `.iter_content()` method and the `.raw` socket interface.* `httpx.codes` - In our documentation we prefer the uppercased versions, such as `codes.NOT_FOUND`, but also provide lower-cased versions for API compatibility with `requests`.* `stream()`. - HTTPX provides a `.stream()` interface rather than using `stream=True`. This ensures that streaming responses are always properly closed outside of the stream block, and makes it visually clearer at which points streaming I/O APIs may be used with a response. Streaming request data is made avialable with `.stream_bytes()`, `.stream_text()`, `.stream_lines()`, and `.stream_raw()`.* `.get`, `.delete`, `.head`, `.options` - These methods do not support `files`, `data`, or `json` arguments. Use `.request` if you need to need to send data using these http methods.* We don't support `response.is_ok` since the naming is ambiguous there, and might incorrectly imply an equivalence to `response.status_code == codes.OK`. Instead we provide an `.is_error` property.* We don't support `response.is_ok` since the naming is ambiguous there, and might incorrectly imply an equivalence to `response.status_code == codes.OK`. Instead we provide the `response.is_error` property. Use `if not response.is_error:` instead of `if response.is_ok:`.
## Advanced Usage
### requests.Session18 unmodified linesmodified:docs/quickstart.md+48 added-2 removed
290 unmodified lines291 >>> r.headers.get('content-type')292 'application/json'293 ```294 295-Multiple values for a single response header are represented as a single comma-separated296-value, as per [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2):295+Multiple 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):296 297 > 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.298 299+## Streaming Responses300+301+For large downloads you may want to use streaming responses that do not load the entire response body into memory at once.302+303+You can stream the binary content of the response...304+305+```306+>>> async with httpx.stream("GET", "https://www.example.com") as r:307+... async for data in r.stream_bytes():308+... print(data)309+```310+311+Or the text of the response...312+313+```314+>>> async with httpx.stream("GET", "https://www.example.com") as r:315+... async for text in r.stream_text():316+... print(text)317+```318+319+Or stream the text, on a line-by-line basis...320+321+```322+>>> async with httpx.stream("GET", "https://www.example.com") as r:323+... async for line in r.stream_lines():324+... print(line)325+```326+327+HTTPX will use universal line endings, normalising all cases to `\n`.328+329+In 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.330+331+```332+>>> async with httpx.stream("GET", "https://www.example.com") as r:333+... async for chunk in r.stream_raw():334+... print(chunk)335+```336+337+If 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:338+339+```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+```345+346 ## Cookies347 348 Any cookies that are set on the response can be easily accessed:349 110 unmodified linesmodified:httpx/__init__.py+2 added-1 removed
1 from .__version__ import __description__, __title__, __version__2-from .api import delete, get, head, options, patch, post, put, request2+from .api import delete, get, head, options, patch, post, put, request, stream3 from .auth import BasicAuth, DigestAuth4 from .client import Client5 from .concurrency.asyncio import AsyncioBackend6 from .concurrency.base import (67 unmodified lines74 "post",75 "patch",76 "put",77 "request",78+ "stream",79 "BasicAuth",80 "Client",81 "DigestAuth",82 "AsyncioBackend",54 unmodified linesmodified:httpx/api.py+40 added-1 removed
1 import typing2 3-from .client import Client3+from .client import Client, StreamContextManager4 from .config import DEFAULT_TIMEOUT_CONFIG, CertTypes, TimeoutTypes, VerifyTypes5 from .models import (6 AuthTypes,7 CookieTypes,8 HeaderTypes,9 QueryParamTypes,10+ Request,11 RequestData,12 RequestFiles,13 Response,14 URLTypes,83 unmodified lines98 allow_redirects=allow_redirects,99 )100 101 102+def 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+ )138+139+140 async def get(141 url: URLTypes,142 *,143 params: QueryParamTypes = None,271 unmodified linesmodified:httpx/client.py+79 added
1 import functools2 import typing3+import warnings4 from types import TracebackType5 6 import hstspreload7 214 unmodified lines222 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+ )231+232 request = self.build_request(233 method=method,234 url=url,235 data=data,14 unmodified lines250 trust_env=trust_env,251 )252 return response253 254+ 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+ )286+287 def build_request(288 self,289 method: str,290 url: URLTypes,612 unmodified lines903 new_proxies[str(key)] = _proxy_from_url(dispatcher_or_url)904 else:905 new_proxies[str(key)] = dispatcher_or_url906 return new_proxies907+908+909+class 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_client926+927+ 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.response936+937+ 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 lines61 62 63 async 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()67+68 assert response.status_code == 20067- body = await response.read()69 assert body == b"Hello, world!"70 assert response.content == b"Hello, world!"71 72 73 async 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+ pass77+78 assert response.status_code == 20079 with pytest.raises(httpx.ResponseNotRead):80 response.content81 81 unmodified linesmodified:tests/client/test_client.py+21 added-17 removed
57 unmodified lines58 59 @pytest.mark.asyncio60 async 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!"66 67 68 @pytest.mark.asyncio69 async def test_stream_iterator(server):70+ body = b""71+72 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 += chunk76+77 assert response.status_code == 20073- body = b""74- async for chunk in response.stream_bytes():75- body += chunk78 assert body == b"Hello, world!"79 80 81 @pytest.mark.asyncio82 async def test_raw_iterator(server):83+ body = b""84+85 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 += chunk89+90 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()92 93 94 @pytest.mark.asyncio95 async def test_raise_for_status(server):80 unmodified lines176 177 178 @pytest.mark.asyncio179 async 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)184 185 186 @pytest.mark.asyncio187 async 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()193+194 assert response.elapsed.total_seconds() == pytest.approx(0.1, rel=0.2)modified:tests/test_api.py+11 added
65 unmodified lines66 assert response.reason_phrase == "OK"67 68 69 @pytest.mark.asyncio70+async def test_stream(server):71+ async with httpx.stream("GET", server.url) as response:72+ await response.read()73+74+ assert response.status_code == 20075+ assert response.reason_phrase == "OK"76+ assert response.text == "Hello, world!"77+ assert response.http_version == "HTTP/1.1"78+79+80+@pytest.mark.asyncio81 async 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 lines43 44 async with Client(45 pool_limits=pool_limits, timeout=timeout, backend=backend46 ) as client:47- response = await client.get(server.url, stream=True)48-49- 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/")51-52- await response.read()