Drop StreamContextManager in favour of `contextlib.contextmanager`/`asynccontextmanager` (#1577)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Drop StreamContextManager in favour of using contextlib.contextmanager/asyncontextmanager * Use type: ignore to avoid mypy errors on 3.6
authored by Tom Christie · committed by GitHub · parent ed19995 · Browse files · 6 files·+133 added−129 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+133 added−129 removed
- other:+133 added−129 removed
Provenance
- Commit
8fd5b71- Tree
5b977cb- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
ed19995
6 files changed+133 added−129 removed
modified:docs/index.md+1 added
112 unmodified linesExpand all11311411511611711811912012125 unmodified lines112 unmodified linesExpand all* `certifi` - SSL certificates.* `rfc3986` - URL parsing & normalization. * `idna` - Internationalized domain name support.* `sniffio` - Async library autodetection.* `async_generator` - Backport support for `contextlib.asynccontextmanager`. *(Only required for Python 3.6)** `brotlipy` - Decoding for "brotli" compressed responses. *(Optional)*
A huge amount of credit is due to `requests` for the API layout thatmuch of this work follows, as well as to `urllib3` for plenty of design25 unmodified linesmodified:httpx/_api.py+22 added-23 removed
1 import typing2+from contextlib import contextmanager3 3-from ._client import Client, StreamContextManager4+from ._client import Client5 from ._config import DEFAULT_TIMEOUT_CONFIG5-from ._models import Request, Response6+from ._models import Response7 from ._types import (8 AuthTypes,9 CertTypes,10 CookieTypes,95 unmodified lines106 allow_redirects=allow_redirects,107 )108 109 110+@contextmanager111 def stream(112 method: str,113 url: URLTypes,114 *,10 unmodified lines125 allow_redirects: bool = True,126 verify: VerifyTypes = True,127 cert: CertTypes = None,128 trust_env: bool = True,127-) -> StreamContextManager:129+) -> typing.Iterator[Response]:130 """131 Alternative to `httpx.request()` that streams the response body132 instead of loading it into memory at once.133 2 unmodified lines136 See also: [Streaming Responses][0]137 138 [0]: /quickstart#streaming-responses139 """138- client = Client(proxies=proxies, cert=cert, verify=verify, trust_env=trust_env)139- request = Request(140- method=method,141- url=url,142- params=params,143- content=content,144- data=data,145- files=files,146- json=json,147- headers=headers,148- cookies=cookies,149- )150- return StreamContextManager(151- client=client,152- request=request,153- auth=auth,154- timeout=timeout,155- allow_redirects=allow_redirects,156- close_client=True,157- )140+ with Client(141+ proxies=proxies, cert=cert, verify=verify, trust_env=trust_env142+ ) as client:143+ with client.stream(144+ method=method,145+ url=url,146+ content=content,147+ data=data,148+ files=files,149+ json=json,150+ params=params,151+ headers=headers,152+ cookies=cookies,153+ auth=auth,154+ allow_redirects=allow_redirects,155+ ) as response:156+ yield response157 158 159 def get(160 url: URLTypes,277 unmodified linesmodified:httpx/_client.py+102 added-106 removed
1 import datetime2 import enum3 import typing4 import warnings5+from contextlib import contextmanager6 from types import TracebackType7 8 from .__version__ import __version__9 from ._auth import Auth, BasicAuth, FunctionAuth10+from ._compat import asynccontextmanager11 from ._config import (12 DEFAULT_LIMITS,13 DEFAULT_MAX_REDIRECTS,14 DEFAULT_TIMEOUT_CONFIG,275 unmodified lines290 @params.setter291 def params(self, params: QueryParamTypes) -> None:292 self._params = QueryParams(params)293 292- def stream(293- self,294- method: str,295- url: URLTypes,296- *,297- content: RequestContent = None,298- data: RequestData = None,299- files: RequestFiles = None,300- json: typing.Any = None,301- params: QueryParamTypes = None,302- headers: HeaderTypes = None,303- cookies: CookieTypes = None,304- auth: typing.Union[AuthTypes, UnsetType] = UNSET,305- allow_redirects: bool = True,306- timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,307- ) -> "StreamContextManager":308- """309- Alternative to `httpx.request()` that streams the response body310- instead of loading it into memory at once.311-312- **Parameters**: See `httpx.request`.313-314- See also: [Streaming Responses][0]315-316- [0]: /quickstart#streaming-responses317- """318- request = self.build_request(319- method=method,320- url=url,321- content=content,322- data=data,323- files=files,324- json=json,325- params=params,326- headers=headers,327- cookies=cookies,328- )329- return StreamContextManager(330- client=self,331- request=request,332- auth=auth,333- allow_redirects=allow_redirects,334- timeout=timeout,335- )336-294 def build_request(295 self,296 method: str,297 url: URLTypes,451 unmodified lines749 return self.send(750 request, auth=auth, allow_redirects=allow_redirects, timeout=timeout751 )752 753+ @contextmanager754+ def stream(755+ self,756+ method: str,757+ url: URLTypes,758+ *,759+ content: RequestContent = None,760+ data: RequestData = None,761+ files: RequestFiles = None,762+ json: typing.Any = None,763+ params: QueryParamTypes = None,764+ headers: HeaderTypes = None,765+ cookies: CookieTypes = None,766+ auth: typing.Union[AuthTypes, UnsetType] = UNSET,767+ allow_redirects: bool = True,768+ timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,769+ ) -> typing.Iterator[Response]:770+ """771+ Alternative to `httpx.request()` that streams the response body772+ instead of loading it into memory at once.773+774+ **Parameters**: See `httpx.request`.775+776+ See also: [Streaming Responses][0]777+778+ [0]: /quickstart#streaming-responses779+ """780+ request = self.build_request(781+ method=method,782+ url=url,783+ content=content,784+ data=data,785+ files=files,786+ json=json,787+ params=params,788+ headers=headers,789+ cookies=cookies,790+ )791+ response = self.send(792+ request=request,793+ auth=auth,794+ allow_redirects=allow_redirects,795+ timeout=timeout,796+ stream=True,797+ )798+ try:799+ yield response800+ finally:801+ response.close()802+803 def send(804 self,805 request: Request,806 *,629 unmodified lines1436 request, auth=auth, allow_redirects=allow_redirects, timeout=timeout1437 )1438 return response1439 1440+ @asynccontextmanager1441+ async def stream(1442+ self,1443+ method: str,1444+ url: URLTypes,1445+ *,1446+ content: RequestContent = None,1447+ data: RequestData = None,1448+ files: RequestFiles = None,1449+ json: typing.Any = None,1450+ params: QueryParamTypes = None,1451+ headers: HeaderTypes = None,1452+ cookies: CookieTypes = None,1453+ auth: typing.Union[AuthTypes, UnsetType] = UNSET,1454+ allow_redirects: bool = True,1455+ timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1456+ ) -> typing.AsyncIterator[Response]:1457+ """1458+ Alternative to `httpx.request()` that streams the response body1459+ instead of loading it into memory at once.1460+1461+ **Parameters**: See `httpx.request`.1462+1463+ See also: [Streaming Responses][0]1464+1465+ [0]: /quickstart#streaming-responses1466+ """1467+ request = self.build_request(1468+ method=method,1469+ url=url,1470+ content=content,1471+ data=data,1472+ files=files,1473+ json=json,1474+ params=params,1475+ headers=headers,1476+ cookies=cookies,1477+ )1478+ response = await self.send(1479+ request=request,1480+ auth=auth,1481+ allow_redirects=allow_redirects,1482+ timeout=timeout,1483+ stream=True,1484+ )1485+ try:1486+ yield response1487+ finally:1488+ await response.aclose()1489+1490 async def send(1491 self,1492 request: Request,1493 *,431 unmodified lines1925 f"Unclosed {self!r}. "1926 "See https://www.python-httpx.org/async/#opening-and-closing-clients "1927 "for details."1928 )1872-1873-1874-class StreamContextManager:1875- def __init__(1876- self,1877- client: BaseClient,1878- request: Request,1879- *,1880- auth: typing.Union[AuthTypes, UnsetType] = UNSET,1881- allow_redirects: bool = True,1882- timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1883- close_client: bool = False,1884- ) -> None:1885- self.client = client1886- self.request = request1887- self.auth = auth1888- self.allow_redirects = allow_redirects1889- self.timeout = timeout1890- self.close_client = close_client1891-1892- def __enter__(self) -> "Response":1893- assert isinstance(self.client, Client)1894- self.response = self.client.send(1895- request=self.request,1896- auth=self.auth,1897- allow_redirects=self.allow_redirects,1898- timeout=self.timeout,1899- stream=True,1900- )1901- return self.response1902-1903- def __exit__(1904- self,1905- exc_type: typing.Type[BaseException] = None,1906- exc_value: BaseException = None,1907- traceback: TracebackType = None,1908- ) -> None:1909- assert isinstance(self.client, Client)1910- self.response.close()1911- if self.close_client:1912- self.client.close()1913-1914- async def __aenter__(self) -> "Response":1915- assert isinstance(self.client, AsyncClient)1916- self.response = await self.client.send(1917- request=self.request,1918- auth=self.auth,1919- allow_redirects=self.allow_redirects,1920- timeout=self.timeout,1921- stream=True,1922- )1923- return self.response1924-1925- async def __aexit__(1926- self,1927- exc_type: typing.Type[BaseException] = None,1928- exc_value: BaseException = None,1929- traceback: TracebackType = None,1930- ) -> None:1931- assert isinstance(self.client, AsyncClient)1932- await self.response.aclose()added:httpx/_compat.py+6 added
1+# `contextlib.asynccontextmanager` exists from Python 3.7 onwards.2+# For 3.6 we require the `async_generator` package for a backported version.3+try:4+ from contextlib import asynccontextmanager # type: ignore5+except ImportError: # pragma: no cover6+ from async_generator import asynccontextmanager # type: ignore # noqamodified:README.md+1 added
120 unmodified lines121 * `certifi` - SSL certificates.122 * `rfc3986` - URL parsing & normalization.123 * `idna` - Internationalized domain name support.124 * `sniffio` - Async library autodetection.125+* `async_generator` - Backport support for `contextlib.asynccontextmanager`. *(Only required for Python 3.6)*126 * `brotlipy` - Decoding for "brotli" compressed responses. *(Optional)*127 128 A huge amount of credit is due to `requests` for the API layout that129 much of this work follows, as well as to `urllib3` for plenty of design4 unmodified linesmodified:setup.py+1 added
58 unmodified lines59 "certifi",60 "sniffio",61 "rfc3986[idna2008]>=1.3,<2",62 "httpcore>=0.12.1,<0.13",63+ "async_generator; python_version < '3.7'"64 ],65 extras_require={66 "http2": "h2==3.*",67 "brotli": "brotlipy==0.7.*",18 unmodified lines