Reintroduce sync API. (#735)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* BaseClient and AsyncClient * Introduce 'httpx.Client' * Top level API -> sync * Top level API -> sync * Add WSGI support, drop deprecated imports * Wire up timeouts to urllib3 * Wire up pool_limits * Add urllib3 proxy support * Pull #734 into sync Client * Update AsyncClient docstring * Simpler WSGI implementation * Set body=None when no content * Wrap urllib3 connection/read exceptions
authored by Tom Christie · committed by GitHub · parent 387f047 · Browse files · 18 files·+1149 added−304 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
18 files+1149 added−304 removed
- tests:+185 added−119 removed
- other:+964 added−185 removed
Provenance
- Commit
ee37a76- Tree
fefe0cf- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
387f047
18 files changed+1149 added−304 removed
modified:httpx/dispatch/__init__.py-7 removed
1-"""2-Dispatch classes handle the raw network connections and the implementation3-details of making the HTTP request and receiving the response.4-"""5-from .asgi import ASGIDispatch6-7-__all__ = ["ASGIDispatch"]modified:httpx/dispatch/asgi.py-3 removed
7 unmodified lines8 9 class ASGIDispatch(AsyncDispatcher):10 """11 A custom AsyncDispatcher that handles sending requests directly to an ASGI app.12-12 The simplest way to use this functionality is to use the `app` argument.14- This will automatically infer if 'app' is a WSGI or an ASGI application,15- and will setup an appropriate dispatch class:13 14 ```15 client = httpx.AsyncClient(app=app)16 ```107 unmodified linesmodified:httpx/dispatch/base.py+12 added
10 unmodified lines11 URLTypes,12 )13 14 15+class SyncDispatcher:16+ """17+ Base class for Dispatcher classes, that handle sending the request.18+ """19+20+ def send(self, request: Request, timeout: Timeout = None) -> Response:21+ raise NotImplementedError() # pragma: nocover22+23+ def close(self) -> None:24+ pass # pragma: nocover25+26+27 class AsyncDispatcher:28 """29 Base class for AsyncDispatcher classes, that handle sending the request.30 34 unmodified linesadded:httpx/dispatch/urllib3.py+128 added
1+import math2+import socket3+import ssl4+import typing5+6+import urllib37+from urllib3.exceptions import MaxRetryError, SSLError8+9+from ..config import (10+ DEFAULT_POOL_LIMITS,11+ CertTypes,12+ PoolLimits,13+ Proxy,14+ SSLConfig,15+ Timeout,16+ VerifyTypes,17+)18+from ..content_streams import IteratorStream19+from ..models import Request, Response20+from ..utils import as_network_error21+from .base import SyncDispatcher22+23+24+class URLLib3Dispatcher(SyncDispatcher):25+ def __init__(26+ self,27+ *,28+ proxy: Proxy = None,29+ verify: VerifyTypes = True,30+ cert: CertTypes = None,31+ trust_env: bool = None,32+ pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,33+ ):34+ ssl_config = SSLConfig(35+ verify=verify, cert=cert, trust_env=trust_env, http2=False36+ )37+ hard_limit = pool_limits.hard_limit38+ soft_limit = pool_limits.soft_limit39+40+ # Our connection pool configuration doesn't quite match up with urllib3's41+ # controls, but we can put sensible mappings in place:42+ if hard_limit is None:43+ block = False44+ if soft_limit is None:45+ num_pools = 100046+ maxsize = 100047+ else:48+ num_pools = int(math.sqrt(soft_limit))49+ maxsize = int(math.sqrt(soft_limit))50+ else:51+ block = True52+ num_pools = int(math.sqrt(hard_limit))53+ maxsize = int(math.sqrt(hard_limit))54+55+ self.pool = self.init_pool_manager(56+ proxy=proxy,57+ ssl_context=ssl_config.ssl_context,58+ num_pools=num_pools,59+ maxsize=maxsize,60+ block=block,61+ )62+63+ def init_pool_manager(64+ self,65+ proxy: typing.Optional[Proxy],66+ ssl_context: ssl.SSLContext,67+ num_pools: int,68+ maxsize: int,69+ block: bool,70+ ) -> typing.Union[urllib3.PoolManager, urllib3.ProxyManager]:71+ if proxy is None:72+ return urllib3.PoolManager(73+ ssl_context=ssl_context,74+ num_pools=num_pools,75+ maxsize=maxsize,76+ block=block,77+ )78+ else:79+ return urllib3.ProxyManager(80+ proxy_url=proxy.url,81+ proxy_headers=dict(proxy.headers),82+ ssl_context=ssl_context,83+ num_pools=num_pools,84+ maxsize=maxsize,85+ block=block,86+ )87+88+ def send(self, request: Request, timeout: Timeout = None) -> Response:89+ timeout = Timeout() if timeout is None else timeout90+ urllib3_timeout = urllib3.util.Timeout(91+ connect=timeout.connect_timeout, read=timeout.read_timeout92+ )93+ chunked = request.headers.get("Transfer-Encoding") == "chunked"94+ content_length = int(request.headers.get("Content-Length", "0"))95+ body = request.stream if chunked or content_length else None96+97+ with as_network_error(MaxRetryError, SSLError, socket.error):98+ conn = self.pool.urlopen(99+ method=request.method,100+ url=str(request.url),101+ headers=dict(request.headers),102+ body=body,103+ redirect=False,104+ assert_same_host=False,105+ retries=0,106+ preload_content=False,107+ chunked=chunked,108+ timeout=urllib3_timeout,109+ pool_timeout=timeout.pool_timeout,110+ )111+112+ def response_bytes() -> typing.Iterator[bytes]:113+ with as_network_error(socket.error):114+ for chunk in conn.stream(4096, decode_content=False):115+ yield chunk116+117+ return Response(118+ status_code=conn.status,119+ http_version="HTTP/1.1",120+ headers=list(conn.headers.items()),121+ stream=IteratorStream(122+ iterator=response_bytes(), close_func=conn.release_conn123+ ),124+ request=request,125+ )126+127+ def close(self) -> None:128+ self.pool.clear()added:httpx/dispatch/wsgi.py+103 added
1+import io2+import typing3+4+from ..config import TimeoutTypes5+from ..content_streams import IteratorStream6+from ..models import Request, Response7+from .base import SyncDispatcher8+9+10+class WSGIDispatch(SyncDispatcher):11+ """12+ A custom SyncDispatcher that handles sending requests directly to an WSGI app.13+ The simplest way to use this functionality is to use the `app` argument.14+15+ ```16+ client = httpx.Client(app=app)17+ ```18+19+ Alternatively, you can setup the dispatch instance explicitly.20+ This allows you to include any additional configuration arguments specific21+ to the WSGIDispatch class:22+23+ ```24+ dispatch = httpx.WSGIDispatch(25+ app=app,26+ script_name="/submount",27+ remote_addr="1.2.3.4"28+ )29+ client = httpx.Client(dispatch=dispatch)30+ ```31+32+ Arguments:33+34+ * `app` - The ASGI application.35+ * `raise_app_exceptions` - Boolean indicating if exceptions in the application36+ should be raised. Default to `True`. Can be set to `False` for use cases37+ such as testing the content of a client 500 response.38+ * `script_name` - The root path on which the ASGI application should be mounted.39+ * `remote_addr` - A string indicating the client IP of incoming requests.40+ ```41+ """42+43+ def __init__(44+ self,45+ app: typing.Callable,46+ raise_app_exceptions: bool = True,47+ script_name: str = "",48+ remote_addr: str = "127.0.0.1",49+ ) -> None:50+ self.app = app51+ self.raise_app_exceptions = raise_app_exceptions52+ self.script_name = script_name53+ self.remote_addr = remote_addr54+55+ def send(self, request: Request, timeout: TimeoutTypes = None) -> Response:56+ environ = {57+ "wsgi.version": (1, 0),58+ "wsgi.url_scheme": request.url.scheme,59+ "wsgi.input": io.BytesIO(request.read()),60+ "wsgi.errors": io.BytesIO(),61+ "wsgi.multithread": True,62+ "wsgi.multiprocess": False,63+ "wsgi.run_once": False,64+ "REQUEST_METHOD": request.method,65+ "SCRIPT_NAME": self.script_name,66+ "PATH_INFO": request.url.path,67+ "QUERY_STRING": request.url.query,68+ "SERVER_NAME": request.url.host,69+ "SERVER_PORT": str(request.url.port),70+ "REMOTE_ADDR": self.remote_addr,71+ }72+ for key, value in request.headers.items():73+ key = key.upper().replace("-", "_")74+ if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):75+ key = "HTTP_" + key76+ environ[key] = value77+78+ seen_status = None79+ seen_response_headers = None80+ seen_exc_info = None81+82+ def start_response(83+ status: str, response_headers: list, exc_info: typing.Any = None84+ ) -> None:85+ nonlocal seen_status, seen_response_headers, seen_exc_info86+ seen_status = status87+ seen_response_headers = response_headers88+ seen_exc_info = exc_info89+90+ result = self.app(environ, start_response)91+92+ assert seen_status is not None93+ assert seen_response_headers is not None94+ if seen_exc_info and self.raise_app_exceptions:95+ raise seen_exc_info[1]96+97+ return Response(98+ status_code=int(seen_status.split()[0]),99+ http_version="HTTP/1.1",100+ headers=seen_response_headers,101+ stream=IteratorStream(chunk for chunk in result),102+ request=request,103+ )modified:httpx/__init__.py+4 added-5 removed
1 from .__version__ import __description__, __title__, __version__2 from .api import delete, get, head, options, patch, post, put, request, stream3 from .auth import Auth, BasicAuth, DigestAuth4 from .client import AsyncClient, Client5-from .config import TimeoutConfig # For 0.8 backwards compat.5 from .config import PoolLimits, Proxy, Timeout7-from .dispatch.proxy_http import HTTPProxy, HTTPProxyMode6+from .dispatch.asgi import ASGIDispatch7+from .dispatch.wsgi import WSGIDispatch8 from .exceptions import (9 ConnectionClosed,10 ConnectTimeout,11 CookieConflict,32 unmodified lines44 "put",45 "request",46 "stream",47 "codes",48+ "ASGIDispatch",49 "AsyncClient",50 "Auth",51 "BasicAuth",52 "Client",53 "DigestAuth",54 "PoolLimits",55 "Proxy",56 "Timeout",56- "TimeoutConfig", # For 0.8 backwards compat.57- "HTTPProxy",58- "HTTPProxyMode", # For 0.8 backwards compat.57 "ConnectTimeout",58 "CookieConflict",59 "ConnectionClosed",60 "DecodingError",20 unmodified lines81 "Request",82 "TimeoutException",83 "Response",84 "DigestAuth",85+ "WSGIDispatch",86 ]modified:httpx/api.py+19 added-19 removed
1 import typing2 3 from .auth import AuthTypes4-from .client import AsyncClient, StreamContextManager4+from .client import Client, StreamContextManager5 from .config import DEFAULT_TIMEOUT_CONFIG, CertTypes, TimeoutTypes, VerifyTypes6 from .models import (7 CookieTypes,8 HeaderTypes,5 unmodified lines14 URLTypes,15 )16 17 18-async def request(18+def request(19 method: str,20 url: URLTypes,21 *,22 params: QueryParamTypes = None,56 unmodified lines79 >>> response80 <Response [200 OK]>81 ```82 """83- async with AsyncClient(83+ with Client(84 cert=cert, verify=verify, timeout=timeout, trust_env=trust_env,85 ) as client:86- return await client.request(86+ return client.request(87 method=method,88 url=url,89 data=data,90 files=files,22 unmodified lines113 verify: VerifyTypes = True,114 cert: CertTypes = None,115 trust_env: bool = True,116 ) -> StreamContextManager:117- client = AsyncClient(cert=cert, verify=verify, trust_env=trust_env)117+ client = Client(cert=cert, verify=verify, trust_env=trust_env)118 request = Request(119 method=method,120 url=url,121 params=params,12 unmodified lines134 close_client=True,135 )136 137 138-async def get(138+def get(139 url: URLTypes,140 *,141 params: QueryParamTypes = None,142 headers: HeaderTypes = None,12 unmodified lines155 156 Note that the `data`, `files`, and `json` parameters are not available on157 this function, as `GET` requests should not include a request body.158 """159- return await request(159+ return request(160 "GET",161 url,162 params=params,163 headers=headers,6 unmodified lines170 trust_env=trust_env,171 )172 173 174-async def options(174+def options(175 url: URLTypes,176 *,177 params: QueryParamTypes = None,178 headers: HeaderTypes = None,12 unmodified lines191 192 Note that the `data`, `files`, and `json` parameters are not available on193 this function, as `OPTIONS` requests should not include a request body.194 """195- return await request(195+ return request(196 "OPTIONS",197 url,198 params=params,199 headers=headers,6 unmodified lines206 trust_env=trust_env,207 )208 209 210-async def head(210+def head(211 url: URLTypes,212 *,213 params: QueryParamTypes = None,214 headers: HeaderTypes = None,14 unmodified lines229 this function, as `HEAD` requests should not include a request body. The230 `HEAD` method also differs from the other cases in that `allow_redirects`231 defaults to `False`.232 """233- return await request(233+ return request(234 "HEAD",235 url,236 params=params,237 headers=headers,6 unmodified lines244 trust_env=trust_env,245 )246 247 248-async def post(248+def post(249 url: URLTypes,250 *,251 data: RequestData = None,252 files: RequestFiles = None,12 unmodified lines265 Sends a `POST` request.266 267 **Parameters**: See `httpx.request`.268 """269- return await request(269+ return request(270 "POST",271 url,272 data=data,273 files=files,9 unmodified lines283 trust_env=trust_env,284 )285 286 287-async def put(287+def put(288 url: URLTypes,289 *,290 data: RequestData = None,291 files: RequestFiles = None,12 unmodified lines304 Sends a `PUT` request.305 306 **Parameters**: See `httpx.request`.307 """308- return await request(308+ return request(309 "PUT",310 url,311 data=data,312 files=files,9 unmodified lines322 trust_env=trust_env,323 )324 325 326-async def patch(326+def patch(327 url: URLTypes,328 *,329 data: RequestData = None,330 files: RequestFiles = None,12 unmodified lines343 Sends a `PATCH` request.344 345 **Parameters**: See `httpx.request`.346 """347- return await request(347+ return request(348 "PATCH",349 url,350 data=data,351 files=files,9 unmodified lines361 trust_env=trust_env,362 )363 364 365-async def delete(365+def delete(366 url: URLTypes,367 *,368 params: QueryParamTypes = None,369 headers: HeaderTypes = None,12 unmodified lines382 383 Note that the `data`, `files`, and `json` parameters are not available on384 this function, as `DELETE` requests should not include a request body.385 """386- return await request(386+ return request(387 "DELETE",388 url,389 params=params,390 headers=headers,8 unmodified linesmodified:httpx/client.py+684 added-147 removed
20 unmodified lines21 VerifyTypes,22 )23 from .content_streams import ContentStream24 from .dispatch.asgi import ASGIDispatch25-from .dispatch.base import AsyncDispatcher25+from .dispatch.base import AsyncDispatcher, SyncDispatcher26 from .dispatch.connection_pool import ConnectionPool27 from .dispatch.proxy_http import HTTPProxy28+from .dispatch.urllib3 import URLLib3Dispatcher29+from .dispatch.wsgi import WSGIDispatch30 from .exceptions import (31 HTTPError,32 InvalidURL,33 RedirectLoop,20 unmodified lines54 55 logger = get_logger(__name__)56 57 56-class AsyncClient:57- """58- An asynchronous HTTP client, with connection pooling, HTTP/2, redirects,59- cookie persistence, etc.60-61- Usage:62-63- ```python64- >>> client = httpx.AsyncClient()65- >>> response = client.get('https://example.org')66- ```67-68- **Parameters:**69-70- * **auth** - *(optional)* An authentication class to use when sending71- requests.72- * **params** - *(optional)* Query parameters to include in request URLs, as73- a string, dictionary, or list of two-tuples.74- * **headers** - *(optional)* Dictionary of HTTP headers to include when75- sending requests.76- * **cookies** - *(optional)* Dictionary of Cookie items to include when77- sending requests.78- * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to79- verify the identity of requested hosts. Either `True` (default CA bundle),80- a path to an SSL certificate file, or `False` (disable verification).81- * **cert** - *(optional)* An SSL certificate used by the requested host82- to authenticate the client. Either a path to an SSL certificate file, or83- two-tuple of (certificate file, key file), or a three-tuple of (certificate84- file, key file, password).85- * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be86- enabled. Defaults to `False`.87- * **proxies** - *(optional)* A dictionary mapping HTTP protocols to proxy88- URLs.89- * **timeout** - *(optional)* The timeout configuration to use when sending90- requests.91- * **pool_limits** - *(optional)* The connection pool configuration to use92- when determining the maximum number of concurrently open HTTP connections.93- * **max_redirects** - *(optional)* The maximum number of redirect responses94- that should be followed.95- * **base_url** - *(optional)* A URL to use as the base when building96- request URLs.97- * **dispatch** - *(optional)* A dispatch class to use for sending requests98- over the network.99- * **app** - *(optional)* An ASGI application to send requests to,100- rather than sending actual network requests.101- * **backend** - *(optional)* A concurrency backend to use when issuing102- async requests. Either 'auto', 'asyncio', 'trio', or a `ConcurrencyBackend`103- instance. Defaults to 'auto', for autodetection.104- * **trust_env** - *(optional)* Enables or disables usage of environment105- variables for configuration.106- * **uds** - *(optional)* A path to a Unix domain socket to connect through.107- """108-58+class BaseClient:59 def __init__(60 self,61 *,62 auth: AuthTypes = None,63 params: QueryParamTypes = None,64 headers: HeaderTypes = None,65 cookies: CookieTypes = None,116- verify: VerifyTypes = True,117- cert: CertTypes = None,118- http2: bool = False,119- proxies: ProxiesTypes = None,66 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,121- pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,67 max_redirects: int = DEFAULT_MAX_REDIRECTS,68 base_url: URLTypes = None,124- dispatch: AsyncDispatcher = None,125- app: typing.Callable = None,126- backend: typing.Union[str, ConcurrencyBackend] = "auto",69 trust_env: bool = True,128- uds: str = None,70 ):71 if base_url is None:72 self.base_url = URL("", allow_relative=True)73 else:1 unmodified line75 76 if params is None:77 params = {}78 138- if proxies is None and trust_env:139- proxies = typing.cast(ProxiesTypes, get_environment_proxies())140-79 self.auth = auth80 self._params = QueryParams(params)81 self._headers = Headers(headers)82 self._cookies = Cookies(cookies)1 unmodified line84 self.max_redirects = max_redirects85 self.trust_env = trust_env86 self.netrc = NetRCInfo()87 150- proxy_map = self.get_proxy_map(proxies, trust_env)151-152- self.dispatch = self.init_dispatch(153- verify=verify,154- cert=cert,155- http2=http2,156- pool_limits=pool_limits,157- dispatch=dispatch,158- app=app,159- backend=backend,160- trust_env=trust_env,161- uds=uds,162- )163- self.proxies: typing.Dict[str, AsyncDispatcher] = {164- key: self.init_proxy_dispatch(165- proxy,166- verify=verify,167- cert=cert,168- http2=http2,169- pool_limits=pool_limits,170- backend=backend,171- trust_env=trust_env,172- )173- for key, proxy in proxy_map.items()174- }175-176- def init_dispatch(177- self,178- verify: VerifyTypes = True,179- cert: CertTypes = None,180- http2: bool = False,181- pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,182- dispatch: AsyncDispatcher = None,183- app: typing.Callable = None,184- backend: typing.Union[str, ConcurrencyBackend] = "auto",185- trust_env: bool = True,186- uds: str = None,187- ) -> AsyncDispatcher:188- if dispatch is not None:189- return dispatch190-191- if app is not None:192- return ASGIDispatch(app=app)193-194- return ConnectionPool(195- verify=verify,196- cert=cert,197- http2=http2,198- pool_limits=pool_limits,199- backend=backend,200- trust_env=trust_env,201- uds=uds,202- )203-204- def init_proxy_dispatch(205- self,206- proxy: Proxy,207- verify: VerifyTypes = True,208- cert: CertTypes = None,209- http2: bool = False,210- pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,211- backend: typing.Union[str, ConcurrencyBackend] = "auto",212- trust_env: bool = True,213- ) -> AsyncDispatcher:214- return HTTPProxy(215- proxy_url=proxy.url,216- proxy_headers=proxy.headers,217- proxy_mode=proxy.mode,218- verify=verify,219- cert=cert,220- http2=http2,221- pool_limits=pool_limits,222- backend=backend,223- trust_env=trust_env,224- )225-88 def get_proxy_map(89 self, proxies: typing.Optional[ProxiesTypes], trust_env: bool,90 ) -> typing.Dict[str, Proxy]:91 if proxies is None:289 unmodified lines381 )382 383 return request.stream384 385+386+class Client(BaseClient):387+ """388+ An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.389+390+ Usage:391+392+ ```python393+ >>> client = httpx.Client()394+ >>> response = client.get('https://example.org')395+ ```396+397+ **Parameters:**398+399+ * **auth** - *(optional)* An authentication class to use when sending400+ requests.401+ * **params** - *(optional)* Query parameters to include in request URLs, as402+ a string, dictionary, or list of two-tuples.403+ * **headers** - *(optional)* Dictionary of HTTP headers to include when404+ sending requests.405+ * **cookies** - *(optional)* Dictionary of Cookie items to include when406+ sending requests.407+ * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to408+ verify the identity of requested hosts. Either `True` (default CA bundle),409+ a path to an SSL certificate file, or `False` (disable verification).410+ * **cert** - *(optional)* An SSL certificate used by the requested host411+ to authenticate the client. Either a path to an SSL certificate file, or412+ two-tuple of (certificate file, key file), or a three-tuple of (certificate413+ file, key file, password).414+ * **proxies** - *(optional)* A dictionary mapping HTTP protocols to proxy415+ URLs.416+ * **timeout** - *(optional)* The timeout configuration to use when sending417+ requests.418+ * **pool_limits** - *(optional)* The connection pool configuration to use419+ when determining the maximum number of concurrently open HTTP connections.420+ * **max_redirects** - *(optional)* The maximum number of redirect responses421+ that should be followed.422+ * **base_url** - *(optional)* A URL to use as the base when building423+ request URLs.424+ * **dispatch** - *(optional)* A dispatch class to use for sending requests425+ over the network.426+ * **app** - *(optional)* An ASGI application to send requests to,427+ rather than sending actual network requests.428+ * **trust_env** - *(optional)* Enables or disables usage of environment429+ variables for configuration.430+ """431+432+ def __init__(433+ self,434+ *,435+ auth: AuthTypes = None,436+ params: QueryParamTypes = None,437+ headers: HeaderTypes = None,438+ cookies: CookieTypes = None,439+ verify: VerifyTypes = True,440+ cert: CertTypes = None,441+ proxies: ProxiesTypes = None,442+ timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,443+ pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,444+ max_redirects: int = DEFAULT_MAX_REDIRECTS,445+ base_url: URLTypes = None,446+ dispatch: SyncDispatcher = None,447+ app: typing.Callable = None,448+ trust_env: bool = True,449+ ):450+ super().__init__(451+ auth=auth,452+ params=params,453+ headers=headers,454+ cookies=cookies,455+ timeout=timeout,456+ max_redirects=max_redirects,457+ base_url=base_url,458+ trust_env=trust_env,459+ )460+461+ proxy_map = self.get_proxy_map(proxies, trust_env)462+463+ self.dispatch = self.init_dispatch(464+ verify=verify,465+ cert=cert,466+ pool_limits=pool_limits,467+ dispatch=dispatch,468+ app=app,469+ trust_env=trust_env,470+ )471+ self.proxies: typing.Dict[str, SyncDispatcher] = {472+ key: self.init_proxy_dispatch(473+ proxy,474+ verify=verify,475+ cert=cert,476+ pool_limits=pool_limits,477+ trust_env=trust_env,478+ )479+ for key, proxy in proxy_map.items()480+ }481+482+ def init_dispatch(483+ self,484+ verify: VerifyTypes = True,485+ cert: CertTypes = None,486+ pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,487+ dispatch: SyncDispatcher = None,488+ app: typing.Callable = None,489+ trust_env: bool = True,490+ ) -> SyncDispatcher:491+ if dispatch is not None:492+ return dispatch493+494+ if app is not None:495+ return WSGIDispatch(app=app)496+497+ return URLLib3Dispatcher(498+ verify=verify, cert=cert, pool_limits=pool_limits, trust_env=trust_env,499+ )500+501+ def init_proxy_dispatch(502+ self,503+ proxy: Proxy,504+ verify: VerifyTypes = True,505+ cert: CertTypes = None,506+ pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,507+ trust_env: bool = True,508+ ) -> SyncDispatcher:509+ return URLLib3Dispatcher(510+ proxy=proxy,511+ verify=verify,512+ cert=cert,513+ pool_limits=pool_limits,514+ trust_env=trust_env,515+ )516+517+ def dispatcher_for_url(self, url: URL) -> SyncDispatcher:518+ """519+ Returns the SyncDispatcher instance that should be used for a given URL.520+ This will either be the standard connection pool, or a proxy.521+ """522+ if self.proxies:523+ is_default_port = (url.scheme == "http" and url.port == 80) or (524+ url.scheme == "https" and url.port == 443525+ )526+ hostname = f"{url.host}:{url.port}"527+ proxy_keys = (528+ f"{url.scheme}://{hostname}",529+ f"{url.scheme}://{url.host}" if is_default_port else None,530+ f"all://{hostname}",531+ f"all://{url.host}" if is_default_port else None,532+ url.scheme,533+ "all",534+ )535+ for proxy_key in proxy_keys:536+ if proxy_key and proxy_key in self.proxies:537+ dispatcher = self.proxies[proxy_key]538+ return dispatcher539+540+ return self.dispatch541+542+ def request(543+ self,544+ method: str,545+ url: URLTypes,546+ *,547+ data: RequestData = None,548+ files: RequestFiles = None,549+ json: typing.Any = None,550+ params: QueryParamTypes = None,551+ headers: HeaderTypes = None,552+ cookies: CookieTypes = None,553+ auth: AuthTypes = None,554+ allow_redirects: bool = True,555+ timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,556+ ) -> Response:557+ request = self.build_request(558+ method=method,559+ url=url,560+ data=data,561+ files=files,562+ json=json,563+ params=params,564+ headers=headers,565+ cookies=cookies,566+ )567+ return self.send(568+ request, auth=auth, allow_redirects=allow_redirects, timeout=timeout,569+ )570+571+ def send(572+ self,573+ request: Request,574+ *,575+ stream: bool = False,576+ auth: AuthTypes = None,577+ allow_redirects: bool = True,578+ timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,579+ ) -> Response:580+ if request.url.scheme not in ("http", "https"):581+ raise InvalidURL('URL scheme must be "http" or "https".')582+583+ timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)584+585+ auth = self.build_auth(request, auth)586+587+ response = self.send_handling_redirects(588+ request, auth=auth, timeout=timeout, allow_redirects=allow_redirects,589+ )590+591+ if not stream:592+ try:593+ response.read()594+ finally:595+ response.close()596+597+ return response598+599+ def send_handling_redirects(600+ self,601+ request: Request,602+ auth: Auth,603+ timeout: Timeout,604+ allow_redirects: bool = True,605+ history: typing.List[Response] = None,606+ ) -> Response:607+ if history is None:608+ history = []609+610+ while True:611+ if len(history) > self.max_redirects:612+ raise TooManyRedirects()613+ urls = ((resp.request.method, resp.url) for resp in history)614+ if (request.method, request.url) in urls:615+ raise RedirectLoop()616+617+ response = self.send_handling_auth(618+ request, auth=auth, timeout=timeout, history=history619+ )620+ response.history = list(history)621+622+ if not response.is_redirect:623+ return response624+625+ response.read()626+ request = self.build_redirect_request(request, response)627+ history = history + [response]628+629+ if not allow_redirects:630+ response.call_next = functools.partial(631+ self.send_handling_redirects,632+ request=request,633+ auth=auth,634+ timeout=timeout,635+ allow_redirects=False,636+ history=history,637+ )638+ return response639+640+ def send_handling_auth(641+ self,642+ request: Request,643+ history: typing.List[Response],644+ auth: Auth,645+ timeout: Timeout,646+ ) -> Response:647+ if auth.requires_request_body:648+ request.read()649+650+ auth_flow = auth.auth_flow(request)651+ request = next(auth_flow)652+ while True:653+ response = self.send_single_request(request, timeout)654+ try:655+ next_request = auth_flow.send(response)656+ except StopIteration:657+ return response658+ except BaseException as exc:659+ response.close()660+ raise exc from None661+ else:662+ response.history = list(history)663+ response.read()664+ request = next_request665+ history.append(response)666+667+ def send_single_request(self, request: Request, timeout: Timeout,) -> Response:668+ """669+ Sends a single request, without handling any redirections.670+ """671+672+ dispatcher = self.dispatcher_for_url(request.url)673+674+ try:675+ response = dispatcher.send(request, timeout=timeout)676+ except HTTPError as exc:677+ # Add the original request to any HTTPError unless678+ # there'a already a request attached in the case of679+ # a ProxyError.680+ if exc.request is None:681+ exc.request = request682+ raise683+684+ self.cookies.extract_cookies(response)685+686+ status = f"{response.status_code} {response.reason_phrase}"687+ response_line = f"{response.http_version} {status}"688+ logger.debug(f'HTTP Request: {request.method} {request.url} "{response_line}"')689+690+ return response691+692+ def get(693+ self,694+ url: URLTypes,695+ *,696+ params: QueryParamTypes = None,697+ headers: HeaderTypes = None,698+ cookies: CookieTypes = None,699+ auth: AuthTypes = None,700+ allow_redirects: bool = True,701+ timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,702+ ) -> Response:703+ return self.request(704+ "GET",705+ url,706+ params=params,707+ headers=headers,708+ cookies=cookies,709+ auth=auth,710+ allow_redirects=allow_redirects,711+ timeout=timeout,712+ )713+714+ def options(715+ self,716+ url: URLTypes,717+ *,718+ params: QueryParamTypes = None,719+ headers: HeaderTypes = None,720+ cookies: CookieTypes = None,721+ auth: AuthTypes = None,722+ allow_redirects: bool = True,723+ timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,724+ ) -> Response:725+ return self.request(726+ "OPTIONS",727+ url,728+ params=params,729+ headers=headers,730+ cookies=cookies,731+ auth=auth,732+ allow_redirects=allow_redirects,733+ timeout=timeout,734+ )735+736+ def head(737+ self,738+ url: URLTypes,739+ *,740+ params: QueryParamTypes = None,741+ headers: HeaderTypes = None,742+ cookies: CookieTypes = None,743+ auth: AuthTypes = None,744+ allow_redirects: bool = False, # NOTE: Differs to usual default.745+ timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,746+ ) -> Response:747+ return self.request(748+ "HEAD",749+ url,750+ params=params,751+ headers=headers,752+ cookies=cookies,753+ auth=auth,754+ allow_redirects=allow_redirects,755+ timeout=timeout,756+ )757+758+ def post(759+ self,760+ url: URLTypes,761+ *,762+ data: RequestData = None,763+ files: RequestFiles = None,764+ json: typing.Any = None,765+ params: QueryParamTypes = None,766+ headers: HeaderTypes = None,767+ cookies: CookieTypes = None,768+ auth: AuthTypes = None,769+ allow_redirects: bool = True,770+ timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,771+ ) -> Response:772+ return self.request(773+ "POST",774+ url,775+ data=data,776+ files=files,777+ json=json,778+ params=params,779+ headers=headers,780+ cookies=cookies,781+ auth=auth,782+ allow_redirects=allow_redirects,783+ timeout=timeout,784+ )785+786+ def put(787+ self,788+ url: URLTypes,789+ *,790+ data: RequestData = None,791+ files: RequestFiles = None,792+ json: typing.Any = None,793+ params: QueryParamTypes = None,794+ headers: HeaderTypes = None,795+ cookies: CookieTypes = None,796+ auth: AuthTypes = None,797+ allow_redirects: bool = True,798+ timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,799+ ) -> Response:800+ return self.request(801+ "PUT",802+ url,803+ data=data,804+ files=files,805+ json=json,806+ params=params,807+ headers=headers,808+ cookies=cookies,809+ auth=auth,810+ allow_redirects=allow_redirects,811+ timeout=timeout,812+ )813+814+ def patch(815+ self,816+ url: URLTypes,817+ *,818+ data: RequestData = None,819+ files: RequestFiles = None,820+ json: typing.Any = None,821+ params: QueryParamTypes = None,822+ headers: HeaderTypes = None,823+ cookies: CookieTypes = None,824+ auth: AuthTypes = None,825+ allow_redirects: bool = True,826+ timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,827+ ) -> Response:828+ return self.request(829+ "PATCH",830+ url,831+ data=data,832+ files=files,833+ json=json,834+ params=params,835+ headers=headers,836+ cookies=cookies,837+ auth=auth,838+ allow_redirects=allow_redirects,839+ timeout=timeout,840+ )841+842+ def delete(843+ self,844+ url: URLTypes,845+ *,846+ params: QueryParamTypes = None,847+ headers: HeaderTypes = None,848+ cookies: CookieTypes = None,849+ auth: AuthTypes = None,850+ allow_redirects: bool = True,851+ timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,852+ ) -> Response:853+ return self.request(854+ "DELETE",855+ url,856+ params=params,857+ headers=headers,858+ cookies=cookies,859+ auth=auth,860+ allow_redirects=allow_redirects,861+ timeout=timeout,862+ )863+864+ def close(self) -> None:865+ self.dispatch.close()866+867+ def __enter__(self) -> "Client":868+ return self869+870+ def __exit__(871+ self,872+ exc_type: typing.Type[BaseException] = None,873+ exc_value: BaseException = None,874+ traceback: TracebackType = None,875+ ) -> None:876+ self.close()877+878+879+class AsyncClient(BaseClient):880+ """881+ An asynchronous HTTP client, with connection pooling, HTTP/2, redirects,882+ cookie persistence, etc.883+884+ Usage:885+886+ ```python887+ >>> async with httpx.AsyncClient() as client:888+ >>> response = await client.get('https://example.org')889+ ```890+891+ **Parameters:**892+893+ * **auth** - *(optional)* An authentication class to use when sending894+ requests.895+ * **params** - *(optional)* Query parameters to include in request URLs, as896+ a string, dictionary, or list of two-tuples.897+ * **headers** - *(optional)* Dictionary of HTTP headers to include when898+ sending requests.899+ * **cookies** - *(optional)* Dictionary of Cookie items to include when900+ sending requests.901+ * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to902+ verify the identity of requested hosts. Either `True` (default CA bundle),903+ a path to an SSL certificate file, or `False` (disable verification).904+ * **cert** - *(optional)* An SSL certificate used by the requested host905+ to authenticate the client. Either a path to an SSL certificate file, or906+ two-tuple of (certificate file, key file), or a three-tuple of (certificate907+ file, key file, password).908+ * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be909+ enabled. Defaults to `False`.910+ * **proxies** - *(optional)* A dictionary mapping HTTP protocols to proxy911+ URLs.912+ * **timeout** - *(optional)* The timeout configuration to use when sending913+ requests.914+ * **pool_limits** - *(optional)* The connection pool configuration to use915+ when determining the maximum number of concurrently open HTTP connections.916+ * **max_redirects** - *(optional)* The maximum number of redirect responses917+ that should be followed.918+ * **base_url** - *(optional)* A URL to use as the base when building919+ request URLs.920+ * **dispatch** - *(optional)* A dispatch class to use for sending requests921+ over the network.922+ * **app** - *(optional)* An ASGI application to send requests to,923+ rather than sending actual network requests.924+ * **backend** - *(optional)* A concurrency backend to use when issuing925+ async requests. Either 'auto', 'asyncio', 'trio', or a `ConcurrencyBackend`926+ instance. Defaults to 'auto', for autodetection.927+ * **trust_env** - *(optional)* Enables or disables usage of environment928+ variables for configuration.929+ * **uds** - *(optional)* A path to a Unix domain socket to connect through.930+ """931+932+ def __init__(933+ self,934+ *,935+ auth: AuthTypes = None,936+ params: QueryParamTypes = None,937+ headers: HeaderTypes = None,938+ cookies: CookieTypes = None,939+ verify: VerifyTypes = True,940+ cert: CertTypes = None,941+ http2: bool = False,942+ proxies: ProxiesTypes = None,943+ timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,944+ pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,945+ max_redirects: int = DEFAULT_MAX_REDIRECTS,946+ base_url: URLTypes = None,947+ dispatch: AsyncDispatcher = None,948+ app: typing.Callable = None,949+ backend: typing.Union[str, ConcurrencyBackend] = "auto",950+ trust_env: bool = True,951+ uds: str = None,952+ ):953+ super().__init__(954+ auth=auth,955+ params=params,956+ headers=headers,957+ cookies=cookies,958+ timeout=timeout,959+ max_redirects=max_redirects,960+ base_url=base_url,961+ trust_env=trust_env,962+ )963+964+ proxy_map = self.get_proxy_map(proxies, trust_env)965+966+ self.dispatch = self.init_dispatch(967+ verify=verify,968+ cert=cert,969+ http2=http2,970+ pool_limits=pool_limits,971+ dispatch=dispatch,972+ app=app,973+ backend=backend,974+ trust_env=trust_env,975+ uds=uds,976+ )977+ self.proxies: typing.Dict[str, AsyncDispatcher] = {978+ key: self.init_proxy_dispatch(979+ proxy,980+ verify=verify,981+ cert=cert,982+ http2=http2,983+ pool_limits=pool_limits,984+ backend=backend,985+ trust_env=trust_env,986+ )987+ for key, proxy in proxy_map.items()988+ }989+990+ def init_dispatch(991+ self,992+ verify: VerifyTypes = True,993+ cert: CertTypes = None,994+ http2: bool = False,995+ pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,996+ dispatch: AsyncDispatcher = None,997+ app: typing.Callable = None,998+ backend: typing.Union[str, ConcurrencyBackend] = "auto",999+ trust_env: bool = True,1000+ uds: str = None,1001+ ) -> AsyncDispatcher:1002+ if dispatch is not None:1003+ return dispatch1004+1005+ if app is not None:1006+ return ASGIDispatch(app=app)1007+1008+ return ConnectionPool(1009+ verify=verify,1010+ cert=cert,1011+ http2=http2,1012+ pool_limits=pool_limits,1013+ backend=backend,1014+ trust_env=trust_env,1015+ uds=uds,1016+ )1017+1018+ def init_proxy_dispatch(1019+ self,1020+ proxy: Proxy,1021+ verify: VerifyTypes = True,1022+ cert: CertTypes = None,1023+ http2: bool = False,1024+ pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,1025+ backend: typing.Union[str, ConcurrencyBackend] = "auto",1026+ trust_env: bool = True,1027+ ) -> AsyncDispatcher:1028+ return HTTPProxy(1029+ proxy_url=proxy.url,1030+ proxy_headers=proxy.headers,1031+ proxy_mode=proxy.mode,1032+ verify=verify,1033+ cert=cert,1034+ http2=http2,1035+ pool_limits=pool_limits,1036+ backend=backend,1037+ trust_env=trust_env,1038+ )1039+1040 def dispatcher_for_url(self, url: URL) -> AsyncDispatcher:1041 """1042 Returns the AsyncDispatcher instance that should be used for a given URL.1043 This will either be the standard connection pool, or a proxy.360 unmodified lines1404 1405 class StreamContextManager:1406 def __init__(1407 self,891- client: AsyncClient,1408+ client: BaseClient,1409 request: Request,1410 *,1411 auth: AuthTypes = None,1412 allow_redirects: bool = True,6 unmodified lines1419 self.allow_redirects = allow_redirects1420 self.timeout = timeout1421 self.close_client = close_client1422 1423+ def __enter__(self) -> "Response":1424+ assert isinstance(self.client, Client)1425+ self.response = self.client.send(1426+ request=self.request,1427+ auth=self.auth,1428+ allow_redirects=self.allow_redirects,1429+ timeout=self.timeout,1430+ stream=True,1431+ )1432+ return self.response1433+1434+ def __exit__(1435+ self,1436+ exc_type: typing.Type[BaseException] = None,1437+ exc_value: BaseException = None,1438+ traceback: TracebackType = None,1439+ ) -> None:1440+ assert isinstance(self.client, Client)1441+ self.response.close()1442+ if self.close_client:1443+ self.client.close()1444+1445 async def __aenter__(self) -> "Response":1446+ assert isinstance(self.client, AsyncClient)1447 self.response = await self.client.send(1448 request=self.request,1449 auth=self.auth,1450 allow_redirects=self.allow_redirects,7 unmodified lines1458 exc_type: typing.Type[BaseException] = None,1459 exc_value: BaseException = None,1460 traceback: TracebackType = None,1461 ) -> None:1462+ assert isinstance(self.client, AsyncClient)1463 await self.response.aclose()1464 if self.close_client:1465 await self.client.aclose()925-926-927-# For compatibility with 0.9.x.928-Client = AsyncClientmodified:httpx/config.py-3 removed
328 unmodified lines329 f"mode={self.mode!r})"330 )331 332 333-TimeoutConfig = Timeout # Synonym for backwards compat334-335-333 DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0)334 DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100)335 DEFAULT_MAX_REDIRECTS = 20modified:httpx/models.py+12 added
646 unmodified lines647 if not hasattr(self, "_content"):648 raise RequestNotRead()649 return self._content650 651+ def read(self) -> bytes:652+ """653+ Read and return the request content.654+ """655+ if not hasattr(self, "_content"):656+ self._content = b"".join([part for part in self.stream])657+ # If a streaming request has been read entirely into memory, then658+ # we can replace the stream with a raw bytes implementation,659+ # to ensure that any non-replayable streams can still be used.660+ self.stream = ByteStream(self._content)661+ return self._content662+663 async def aread(self) -> bytes:664 """665 Read and return the request content.666 """538 unmodified linesmodified:tests/client/test_client.py+49 added-76 removed
3 unmodified lines4 5 import httpx6 7 8-@pytest.mark.asyncio9-async def test_get(server):8+def test_get(server):9 url = server.url11- async with httpx.AsyncClient() as http:12- response = await http.get(url)10+ with httpx.Client() as http:11+ response = http.get(url)12 assert response.status_code == 20013 assert response.url == url14 assert response.content == b"Hello, world!"15 assert response.text == "Hello, world!"5 unmodified lines21 assert repr(response) == "<Response [200 OK]>"22 assert response.elapsed > timedelta(0)23 24 26-@pytest.mark.asyncio27-async def test_build_request(server):25+def test_build_request(server):26 url = server.url.copy_with(path="/echo_headers")27 headers = {"Custom-header": "value"}28 31- async with httpx.AsyncClient() as client:29+ with httpx.Client() as client:30 request = client.build_request("GET", url)31 request.headers.update(headers)34- response = await client.send(request)32+ response = client.send(request)33 34 assert response.status_code == 20035 assert response.url == url36 37 assert response.json()["Custom-header"] == "value"38 39 42-@pytest.mark.asyncio43-async def test_post(server):44- async with httpx.AsyncClient() as client:45- response = await client.post(server.url, data=b"Hello, world!")40+def test_post(server):41+ with httpx.Client() as client:42+ response = client.post(server.url, data=b"Hello, world!")43 assert response.status_code == 20044 assert response.reason_phrase == "OK"45 46 50-@pytest.mark.asyncio51-async def test_post_json(server):52- async with httpx.AsyncClient() as client:53- response = await client.post(server.url, json={"text": "Hello, world!"})47+def test_post_json(server):48+ with httpx.Client() as client:49+ response = client.post(server.url, json={"text": "Hello, world!"})50 assert response.status_code == 20051 assert response.reason_phrase == "OK"52 53 58-@pytest.mark.asyncio59-async def test_stream_response(server):60- async with httpx.AsyncClient() as client:61- async with client.stream("GET", server.url) as response:62- content = await response.aread()54+def test_stream_response(server):55+ with httpx.Client() as client:56+ with client.stream("GET", server.url) as response:57+ content = response.read()58 assert response.status_code == 20059 assert content == b"Hello, world!"60 61 67-@pytest.mark.asyncio68-async def test_stream_iterator(server):62+def test_stream_iterator(server):63 body = b""64 71- async with httpx.AsyncClient() as client:72- async with client.stream("GET", server.url) as response:73- async for chunk in response.aiter_bytes():65+ with httpx.Client() as client:66+ with client.stream("GET", server.url) as response:67+ for chunk in response.iter_bytes():68 body += chunk69 70 assert response.status_code == 20071 assert body == b"Hello, world!"72 73 80-@pytest.mark.asyncio81-async def test_raw_iterator(server):74+def test_raw_iterator(server):75 body = b""76 84- async with httpx.AsyncClient() as client:85- async with client.stream("GET", server.url) as response:86- async for chunk in response.aiter_raw():77+ with httpx.Client() as client:78+ with client.stream("GET", server.url) as response:79+ for chunk in response.iter_raw():80 body += chunk81 82 assert response.status_code == 20083 assert body == b"Hello, world!"84 85 93-@pytest.mark.asyncio94-async def test_raise_for_status(server):95- async with httpx.AsyncClient() as client:86+def test_raise_for_status(server):87+ with httpx.Client() as client:88 for status_code in (200, 400, 404, 500, 505):97- response = await client.request(89+ response = client.request(90 "GET", server.url.copy_with(path="/status/{}".format(status_code))91 )92 if 400 <= status_code < 600:93 with pytest.raises(httpx.HTTPError) as exc_info:2 unmodified lines96 else:97 assert response.raise_for_status() is None98 99 108-@pytest.mark.asyncio109-async def test_options(server):110- async with httpx.AsyncClient() as client:111- response = await client.options(server.url)100+def test_options(server):101+ with httpx.Client() as client:102+ response = client.options(server.url)103 assert response.status_code == 200104 assert response.reason_phrase == "OK"105 106 116-@pytest.mark.asyncio117-async def test_head(server):118- async with httpx.AsyncClient() as client:119- response = await client.head(server.url)107+def test_head(server):108+ with httpx.Client() as client:109+ response = client.head(server.url)110 assert response.status_code == 200111 assert response.reason_phrase == "OK"112 113 124-@pytest.mark.asyncio125-async def test_put(server):126- async with httpx.AsyncClient() as client:127- response = await client.put(server.url, data=b"Hello, world!")114+def test_put(server):115+ with httpx.Client() as client:116+ response = client.put(server.url, data=b"Hello, world!")117 assert response.status_code == 200118 assert response.reason_phrase == "OK"119 120 132-@pytest.mark.asyncio133-async def test_patch(server):134- async with httpx.AsyncClient() as client:135- response = await client.patch(server.url, data=b"Hello, world!")121+def test_patch(server):122+ with httpx.Client() as client:123+ response = client.patch(server.url, data=b"Hello, world!")124 assert response.status_code == 200125 assert response.reason_phrase == "OK"126 127 140-@pytest.mark.asyncio141-async def test_delete(server):142- async with httpx.AsyncClient() as client:143- response = await client.delete(server.url)128+def test_delete(server):129+ with httpx.Client() as client:130+ response = client.delete(server.url)131 assert response.status_code == 200132 assert response.reason_phrase == "OK"133 134 148-@pytest.mark.asyncio149-async def test_base_url(server):135+def test_base_url(server):136 base_url = server.url151- async with httpx.AsyncClient(base_url=base_url) as client:152- response = await client.get("/")137+ with httpx.Client(base_url=base_url) as client:138+ response = client.get("/")139 assert response.status_code == 200140 assert response.url == base_url141 142 157-@pytest.mark.asyncio158-async def test_uds(uds_server):159- url = uds_server.url160- uds = uds_server.config.uds161- assert uds is not None162- async with httpx.AsyncClient(uds=uds) as client:163- response = await client.get(url)164- assert response.status_code == 200165- assert response.text == "Hello, world!"166- assert response.encoding == "iso-8859-1"167-168-143 def test_merge_url():170- client = httpx.AsyncClient(base_url="https://www.paypal.com/")144+ client = httpx.Client(base_url="https://www.paypal.com/")145 url = client.merge_url("http://www.paypal.com")146 147 assert url.scheme == "https"148 assert url.is_ssl149 150 177-@pytest.mark.asyncio178-async def test_elapsed_delay(server):151+def test_elapsed_delay(server):152 url = server.url.copy_with(path="/slow_response/100")180- async with httpx.AsyncClient() as client:181- response = await client.get(url)153+ with httpx.Client() as client:154+ response = client.get(url)155 assert response.elapsed.total_seconds() > 0.0modified:tests/client/test_proxies.py-1 removed
79 unmodified lines80 81 if expected is None:82 assert dispatcher is client.dispatch83 else:84- assert isinstance(dispatcher, httpx.HTTPProxy)84 assert dispatcher.proxy_url == expected85 86 87 def test_unsupported_proxy_scheme():2 unmodified linesmodified:tests/dispatch/test_proxy_http.py+7 added-6 removed
1 import pytest2 3 import httpx4+from httpx.dispatch.proxy_http import HTTPProxy5 6 from .utils import MockRawSocketBackend7 8 12 unmodified lines21 b"\r\n",22 ]23 ),24 )24- async with httpx.HTTPProxy(25+ async with HTTPProxy(26 proxy_url="http://127.0.0.1:8000", backend=raw_io, proxy_mode="TUNNEL_ONLY",27 ) as proxy:28 response = await proxy.request("GET", "http://example.com")29 27 unmodified lines57 ),58 )59 60 with pytest.raises(httpx.ProxyError) as e:60- async with httpx.HTTPProxy(61+ async with HTTPProxy(62 proxy_url="http://127.0.0.1:8000", backend=raw_io, proxy_mode="TUNNEL_ONLY",63 ) as proxy:64 await proxy.request("GET", "http://example.com")65 41 unmodified lines107 b"\r\n",108 ]109 ),110 )110- async with httpx.HTTPProxy(111+ async with HTTPProxy(112 proxy_url="http://127.0.0.1:8000", backend=raw_io, proxy_mode="TUNNEL_ONLY",113 ) as proxy:114 resp = await proxy.request("GET", "https://example.com")115 41 unmodified lines157 b"\r\n"158 ]159 ),160 )160- async with httpx.HTTPProxy(161+ async with HTTPProxy(162 proxy_url="http://127.0.0.1:8000",163 backend=raw_io,164 proxy_mode=proxy_mode,165 proxy_headers={"Proxy-Authorization": "test", "Override": "2"},20 unmodified lines186 assert b"override: 1" in recv[1]187 188 189 def test_proxy_url_with_username_and_password():189- proxy = httpx.HTTPProxy("http://user:password@example.com:1080")190+ proxy = HTTPProxy("http://user:password@example.com:1080")191 192 assert proxy.proxy_url == "http://example.com:1080"193 assert proxy.proxy_headers["Proxy-Authorization"] == "Basic dXNlcjpwYXNzd29yZA=="194 195 196 def test_proxy_repr():196- proxy = httpx.HTTPProxy(197+ proxy = HTTPProxy(198 "http://127.0.0.1:1080",199 proxy_headers={"Custom": "Header"},200 proxy_mode="DEFAULT",201 )6 unmodified linesmodified:tests/models/test_requests.py+14 added-7 removed
16 unmodified lines17 request = httpx.Request("POST", "http://example.org", data=b"test 123")18 assert request.headers["Content-Length"] == "8"19 20 21-@pytest.mark.asyncio22-async def test_url_encoded_data():21+def test_url_encoded_data():22 request = httpx.Request("POST", "http://example.org", data={"test": "123"})24- await request.aread()23+ request.read()24 25 assert request.headers["Content-Type"] == "application/x-www-form-urlencoded"26 assert request.content == b"test=123"27 28 30-@pytest.mark.asyncio31-async def test_json_encoded_data():29+def test_json_encoded_data():30 request = httpx.Request("POST", "http://example.org", json={"test": 123})33- await request.aread()31+ request.read()32 33 assert request.headers["Content-Type"] == "application/json"34 assert request.content == b'{"test": 123}'35 36 37+def test_read_and_stream_data():38+ # Ensure a request may still be streamed if it has been read.39+ # Needed for cases such as authentication classes that read the request body.40+ request = httpx.Request("POST", "http://example.org", json={"test": 123})41+ request.read()42+ content = b"".join([part for part in request.stream])43+ assert content == request.content44+45+46 @pytest.mark.asyncio40-async def test_read_and_stream_data():47+async def test_aread_and_stream_data():48 # Ensure a request may still be streamed if it has been read.49 # Needed for cases such as authentication classes that read the request body.50 request = httpx.Request("POST", "http://example.org", json={"test": 123})51 await request.aread()69 unmodified linesmodified:tests/test_api.py+20 added-29 removed
1 unmodified line2 3 import httpx4 5 6-@pytest.mark.asyncio7-async def test_get(server):8- response = await httpx.get(server.url)6+def test_get(server):7+ response = httpx.get(server.url)8 assert response.status_code == 2009 assert response.reason_phrase == "OK"10 assert response.text == "Hello, world!"11 assert response.http_version == "HTTP/1.1"12 13 15-@pytest.mark.asyncio16-async def test_post(server):17- response = await httpx.post(server.url, data=b"Hello, world!")14+def test_post(server):15+ response = httpx.post(server.url, data=b"Hello, world!")16 assert response.status_code == 20017 assert response.reason_phrase == "OK"18 19 22-@pytest.mark.asyncio23-async def test_post_byte_iterator(server):24- async def data():20+def test_post_byte_iterator(server):21+ def data():22 yield b"Hello"23 yield b", "24 yield b"world!"25 29- response = await httpx.post(server.url, data=data())26+ response = httpx.post(server.url, data=data())27 assert response.status_code == 20028 assert response.reason_phrase == "OK"29 30 34-@pytest.mark.asyncio35-async def test_options(server):36- response = await httpx.options(server.url)31+def test_options(server):32+ response = httpx.options(server.url)33 assert response.status_code == 20034 assert response.reason_phrase == "OK"35 36 41-@pytest.mark.asyncio42-async def test_head(server):43- response = await httpx.head(server.url)37+def test_head(server):38+ response = httpx.head(server.url)39 assert response.status_code == 20040 assert response.reason_phrase == "OK"41 42 48-@pytest.mark.asyncio49-async def test_put(server):50- response = await httpx.put(server.url, data=b"Hello, world!")43+def test_put(server):44+ response = httpx.put(server.url, data=b"Hello, world!")45 assert response.status_code == 20046 assert response.reason_phrase == "OK"47 48 55-@pytest.mark.asyncio56-async def test_patch(server):57- response = await httpx.patch(server.url, data=b"Hello, world!")49+def test_patch(server):50+ response = httpx.patch(server.url, data=b"Hello, world!")51 assert response.status_code == 20052 assert response.reason_phrase == "OK"53 54 62-@pytest.mark.asyncio63-async def test_delete(server):64- response = await httpx.delete(server.url)55+def test_delete(server):56+ response = httpx.delete(server.url)57 assert response.status_code == 20058 assert response.reason_phrase == "OK"59 60 69-@pytest.mark.asyncio70-async def test_stream(server):71- async with httpx.stream("GET", server.url) as response:72- await response.aread()61+def test_stream(server):62+ with httpx.stream("GET", server.url) as response:63+ response.read()64 65 assert response.status_code == 20066 assert response.reason_phrase == "OK"67 assert response.text == "Hello, world!"7 unmodified linesadded:tests/test_wsgi.py+95 added
1+import sys2+3+import pytest4+5+import httpx6+7+8+def hello_world(environ, start_response):9+ status = "200 OK"10+ output = b"Hello, World!"11+12+ response_headers = [13+ ("Content-type", "text/plain"),14+ ("Content-Length", str(len(output))),15+ ]16+17+ start_response(status, response_headers)18+19+ return [output]20+21+22+def echo_body(environ, start_response):23+ status = "200 OK"24+ output = environ["wsgi.input"].read()25+26+ response_headers = [27+ ("Content-type", "text/plain"),28+ ("Content-Length", str(len(output))),29+ ]30+31+ start_response(status, response_headers)32+33+ return [output]34+35+36+def echo_body_with_response_stream(environ, start_response):37+ status = "200 OK"38+39+ response_headers = [("Content-Type", "text/plain")]40+41+ start_response(status, response_headers)42+43+ def output_generator(f):44+ while True:45+ output = f.read(2)46+ if not output:47+ break48+ yield output49+50+ return output_generator(f=environ["wsgi.input"])51+52+53+def raise_exc(environ, start_response):54+ status = "500 Server Error"55+ output = b"Nope!"56+57+ response_headers = [58+ ("Content-type", "text/plain"),59+ ("Content-Length", str(len(output))),60+ ]61+62+ try:63+ raise ValueError()64+ except ValueError:65+ exc_info = sys.exc_info()66+ start_response(status, response_headers, exc_info=exc_info)67+68+ return [output]69+70+71+def test_wsgi():72+ client = httpx.Client(app=hello_world)73+ response = client.get("http://www.example.org/")74+ assert response.status_code == 20075+ assert response.text == "Hello, World!"76+77+78+def test_wsgi_upload():79+ client = httpx.Client(app=echo_body)80+ response = client.post("http://www.example.org/", data=b"example")81+ assert response.status_code == 20082+ assert response.text == "example"83+84+85+def test_wsgi_upload_with_response_stream():86+ client = httpx.Client(app=echo_body_with_response_stream)87+ response = client.post("http://www.example.org/", data=b"example")88+ assert response.status_code == 20089+ assert response.text == "example"90+91+92+def test_wsgi_exc():93+ client = httpx.Client(app=raise_exc)94+ with pytest.raises(ValueError):95+ client.get("http://www.example.org/")modified:setup.cfg+1 added-1 removed
12 unmodified lines13 combine_as_imports = True14 force_grid_wrap = 015 include_trailing_comma = True16 known_first_party = httpx,tests17-known_third_party = brotli,certifi,chardet,cryptography,h11,h2,hstspreload,pytest,rfc3986,setuptools,sniffio,trio,trustme,uvicorn17+known_third_party = brotli,certifi,chardet,cryptography,h11,h2,hstspreload,pytest,rfc3986,setuptools,sniffio,trio,trustme,urllib3,uvicorn18 line_length = 8819 multi_line_output = 320 21 [tool:pytest]3 unmodified linesmodified:setup.py+1 added
57 unmodified lines58 "h2==3.*",59 "idna==2.*",60 "rfc3986>=1.3,<2",61 "sniffio==1.*",62+ "urllib3==1.*",63 ],64 classifiers=[65 "Development Status :: 3 - Alpha",66 "Environment :: Web Environment",12 unmodified lines