Skip to content
Myr

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

18 files+1149 added−304 removed

modified:httpx/dispatch/__init__.py-7 removed
1"""2Dispatch classes handle the raw network connections and the implementation3details of making the HTTP request and receiving the response.4"""5from .asgi import ASGIDispatch67__all__ = ["ASGIDispatch"]
modified:httpx/dispatch/asgi.py-3 removed
7 unmodified lines
89class ASGIDispatch(AsyncDispatcher):10 """11 A custom AsyncDispatcher that handles sending requests directly to an ASGI app.1212 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:1314 ```15 client = httpx.AsyncClient(app=app)16 ```
107 unmodified lines
modified:httpx/dispatch/base.py+12 added
10 unmodified lines
11 URLTypes,12)131415class SyncDispatcher:16 """17 Base class for Dispatcher classes, that handle sending the request.18 """1920 def send(self, request: Request, timeout: Timeout = None) -> Response:21 raise NotImplementedError() # pragma: nocover2223 def close(self) -> None:24 pass # pragma: nocover252627class AsyncDispatcher:28 """29 Base class for AsyncDispatcher classes, that handle sending the request.30
34 unmodified lines
added:httpx/dispatch/urllib3.py+128 added
1import math2import socket3import ssl4import typing56import urllib37from urllib3.exceptions import MaxRetryError, SSLError89from ..config import (10 DEFAULT_POOL_LIMITS,11 CertTypes,12 PoolLimits,13 Proxy,14 SSLConfig,15 Timeout,16 VerifyTypes,17)18from ..content_streams import IteratorStream19from ..models import Request, Response20from ..utils import as_network_error21from .base import SyncDispatcher222324class 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_limit3940 # 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))5455 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 )6263 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 )8788 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 None9697 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 )111112 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 chunk116117 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 )126127 def close(self) -> None:128 self.pool.clear()
added:httpx/dispatch/wsgi.py+103 added
1import io2import typing34from ..config import TimeoutTypes5from ..content_streams import IteratorStream6from ..models import Request, Response7from .base import SyncDispatcher8910class 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.1415 ```16 client = httpx.Client(app=app)17 ```1819 Alternatively, you can setup the dispatch instance explicitly.20 This allows you to include any additional configuration arguments specific21 to the WSGIDispatch class:2223 ```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 ```3132 Arguments:3334 * `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 """4243 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_addr5455 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] = value7778 seen_status = None79 seen_response_headers = None80 seen_exc_info = None8182 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_info8990 result = self.app(environ, start_response)9192 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]9697 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
1from .__version__ import __description__, __title__, __version__2from .api import delete, get, head, options, patch, post, put, request, stream3from .auth import Auth, BasicAuth, DigestAuth4from .client import AsyncClient, Client5from .config import TimeoutConfig # For 0.8 backwards compat.5from .config import PoolLimits, Proxy, Timeout7from .dispatch.proxy_http import HTTPProxy, HTTPProxyMode6from .dispatch.asgi import ASGIDispatch7from .dispatch.wsgi import WSGIDispatch8from .exceptions import (9 ConnectionClosed,10 ConnectTimeout,11 CookieConflict,
32 unmodified lines
44 "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 lines
81 "Request",82 "TimeoutException",83 "Response",84 "DigestAuth",85 "WSGIDispatch",86]
modified:httpx/api.py+19 added-19 removed
1import typing23from .auth import AuthTypes4from .client import AsyncClient, StreamContextManager4from .client import Client, StreamContextManager5from .config import DEFAULT_TIMEOUT_CONFIG, CertTypes, TimeoutTypes, VerifyTypes6from .models import (7 CookieTypes,8 HeaderTypes,
5 unmodified lines
14 URLTypes,15)161718async def request(18def request(19 method: str,20 url: URLTypes,21 *,22 params: QueryParamTypes = None,
56 unmodified lines
79 >>> 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 lines
113 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 lines
134 close_client=True,135 )136137138async def get(138def get(139 url: URLTypes,140 *,141 params: QueryParamTypes = None,142 headers: HeaderTypes = None,
12 unmodified lines
155156 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 lines
170 trust_env=trust_env,171 )172173174async def options(174def options(175 url: URLTypes,176 *,177 params: QueryParamTypes = None,178 headers: HeaderTypes = None,
12 unmodified lines
191192 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 lines
206 trust_env=trust_env,207 )208209210async def head(210def head(211 url: URLTypes,212 *,213 params: QueryParamTypes = None,214 headers: HeaderTypes = None,
14 unmodified lines
229 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 lines
244 trust_env=trust_env,245 )246247248async def post(248def post(249 url: URLTypes,250 *,251 data: RequestData = None,252 files: RequestFiles = None,
12 unmodified lines
265 Sends a `POST` request.266267 **Parameters**: See `httpx.request`.268 """269 return await request(269 return request(270 "POST",271 url,272 data=data,273 files=files,
9 unmodified lines
283 trust_env=trust_env,284 )285286287async def put(287def put(288 url: URLTypes,289 *,290 data: RequestData = None,291 files: RequestFiles = None,
12 unmodified lines
304 Sends a `PUT` request.305306 **Parameters**: See `httpx.request`.307 """308 return await request(308 return request(309 "PUT",310 url,311 data=data,312 files=files,
9 unmodified lines
322 trust_env=trust_env,323 )324325326async def patch(326def patch(327 url: URLTypes,328 *,329 data: RequestData = None,330 files: RequestFiles = None,
12 unmodified lines
343 Sends a `PATCH` request.344345 **Parameters**: See `httpx.request`.346 """347 return await request(347 return request(348 "PATCH",349 url,350 data=data,351 files=files,
9 unmodified lines
361 trust_env=trust_env,362 )363364365async def delete(365def delete(366 url: URLTypes,367 *,368 params: QueryParamTypes = None,369 headers: HeaderTypes = None,
12 unmodified lines
382383 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 lines
modified:httpx/client.py+684 added-147 removed
20 unmodified lines
21 VerifyTypes,22)23from .content_streams import ContentStream24from .dispatch.asgi import ASGIDispatch25from .dispatch.base import AsyncDispatcher25from .dispatch.base import AsyncDispatcher, SyncDispatcher26from .dispatch.connection_pool import ConnectionPool27from .dispatch.proxy_http import HTTPProxy28from .dispatch.urllib3 import URLLib3Dispatcher29from .dispatch.wsgi import WSGIDispatch30from .exceptions import (31 HTTPError,32 InvalidURL,33 RedirectLoop,
20 unmodified lines
5455logger = get_logger(__name__)565756class AsyncClient:57 """58 An asynchronous HTTP client, with connection pooling, HTTP/2, redirects,59 cookie persistence, etc.6061 Usage:6263 ```python64 >>> client = httpx.AsyncClient()65 >>> response = client.get('https://example.org')66 ```6768 **Parameters:**6970 * **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 """10858class 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 line
7576 if params is None:77 params = {}78138 if proxies is None and trust_env:139 proxies = typing.cast(ProxiesTypes, get_environment_proxies())14079 self.auth = auth80 self._params = QueryParams(params)81 self._headers = Headers(headers)82 self._cookies = Cookies(cookies)
1 unmodified line
84 self.max_redirects = max_redirects85 self.trust_env = trust_env86 self.netrc = NetRCInfo()87150 proxy_map = self.get_proxy_map(proxies, trust_env)151152 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 }175176 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 dispatch190191 if app is not None:192 return ASGIDispatch(app=app)193194 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 )203204 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 )22588 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 lines
381 )382383 return request.stream384385386class Client(BaseClient):387 """388 An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.389390 Usage:391392 ```python393 >>> client = httpx.Client()394 >>> response = client.get('https://example.org')395 ```396397 **Parameters:**398399 * **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 """431432 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 )460461 proxy_map = self.get_proxy_map(proxies, trust_env)462463 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 }481482 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 dispatch493494 if app is not None:495 return WSGIDispatch(app=app)496497 return URLLib3Dispatcher(498 verify=verify, cert=cert, pool_limits=pool_limits, trust_env=trust_env,499 )500501 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 )516517 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 dispatcher539540 return self.dispatch541542 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 )570571 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".')582583 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)584585 auth = self.build_auth(request, auth)586587 response = self.send_handling_redirects(588 request, auth=auth, timeout=timeout, allow_redirects=allow_redirects,589 )590591 if not stream:592 try:593 response.read()594 finally:595 response.close()596597 return response598599 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 = []609610 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()616617 response = self.send_handling_auth(618 request, auth=auth, timeout=timeout, history=history619 )620 response.history = list(history)621622 if not response.is_redirect:623 return response624625 response.read()626 request = self.build_redirect_request(request, response)627 history = history + [response]628629 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 response639640 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()649650 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)666667 def send_single_request(self, request: Request, timeout: Timeout,) -> Response:668 """669 Sends a single request, without handling any redirections.670 """671672 dispatcher = self.dispatcher_for_url(request.url)673674 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 raise683684 self.cookies.extract_cookies(response)685686 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}"')689690 return response691692 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 )713714 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 )735736 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 )757758 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 )785786 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 )813814 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 )841842 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 )863864 def close(self) -> None:865 self.dispatch.close()866867 def __enter__(self) -> "Client":868 return self869870 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()877878879class AsyncClient(BaseClient):880 """881 An asynchronous HTTP client, with connection pooling, HTTP/2, redirects,882 cookie persistence, etc.883884 Usage:885886 ```python887 >>> async with httpx.AsyncClient() as client:888 >>> response = await client.get('https://example.org')889 ```890891 **Parameters:**892893 * **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 """931932 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 )963964 proxy_map = self.get_proxy_map(proxies, trust_env)965966 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 }989990 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 dispatch10041005 if app is not None:1006 return ASGIDispatch(app=app)10071008 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 )10171018 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 )10391040 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 lines
14041405class 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 lines
1419 self.allow_redirects = allow_redirects1420 self.timeout = timeout1421 self.close_client = close_client14221423 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.response14331434 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()14441445 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 lines
1458 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()925926927# For compatibility with 0.9.x.928Client = AsyncClient
modified:httpx/config.py-3 removed
328 unmodified lines
329 f"mode={self.mode!r})"330 )331332333TimeoutConfig = Timeout # Synonym for backwards compat334335333DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0)334DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100)335DEFAULT_MAX_REDIRECTS = 20
modified:httpx/models.py+12 added
646 unmodified lines
647 if not hasattr(self, "_content"):648 raise RequestNotRead()649 return self._content650651 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._content662663 async def aread(self) -> bytes:664 """665 Read and return the request content.666 """
538 unmodified lines
modified:tests/client/test_client.py+49 added-76 removed
3 unmodified lines
45import httpx678@pytest.mark.asyncio9async def test_get(server):8def 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 lines
21 assert repr(response) == "<Response [200 OK]>"22 assert response.elapsed > timedelta(0)232426@pytest.mark.asyncio27async def test_build_request(server):25def test_build_request(server):26 url = server.url.copy_with(path="/echo_headers")27 headers = {"Custom-header": "value"}2831 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)3334 assert response.status_code == 20035 assert response.url == url3637 assert response.json()["Custom-header"] == "value"383942@pytest.mark.asyncio43async def test_post(server):44 async with httpx.AsyncClient() as client:45 response = await client.post(server.url, data=b"Hello, world!")40def 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"454650@pytest.mark.asyncio51async def test_post_json(server):52 async with httpx.AsyncClient() as client:53 response = await client.post(server.url, json={"text": "Hello, world!"})47def 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"525358@pytest.mark.asyncio59async 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()54def 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!"606167@pytest.mark.asyncio68async def test_stream_iterator(server):62def test_stream_iterator(server):63 body = b""6471 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 += chunk6970 assert response.status_code == 20071 assert body == b"Hello, world!"727380@pytest.mark.asyncio81async def test_raw_iterator(server):74def test_raw_iterator(server):75 body = b""7684 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 += chunk8182 assert response.status_code == 20083 assert body == b"Hello, world!"848593@pytest.mark.asyncio94async def test_raise_for_status(server):95 async with httpx.AsyncClient() as client:86def 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 lines
96 else:97 assert response.raise_for_status() is None9899108@pytest.mark.asyncio109async def test_options(server):110 async with httpx.AsyncClient() as client:111 response = await client.options(server.url)100def 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"105106116@pytest.mark.asyncio117async def test_head(server):118 async with httpx.AsyncClient() as client:119 response = await client.head(server.url)107def 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"112113124@pytest.mark.asyncio125async def test_put(server):126 async with httpx.AsyncClient() as client:127 response = await client.put(server.url, data=b"Hello, world!")114def 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"119120132@pytest.mark.asyncio133async def test_patch(server):134 async with httpx.AsyncClient() as client:135 response = await client.patch(server.url, data=b"Hello, world!")121def 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"126127140@pytest.mark.asyncio141async def test_delete(server):142 async with httpx.AsyncClient() as client:143 response = await client.delete(server.url)128def 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"133134148@pytest.mark.asyncio149async def test_base_url(server):135def 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_url141142157@pytest.mark.asyncio158async 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"167168143def 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")146147 assert url.scheme == "https"148 assert url.is_ssl149150177@pytest.mark.asyncio178async def test_elapsed_delay(server):151def 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.0
modified:tests/client/test_proxies.py-1 removed
79 unmodified lines
8081 if expected is None:82 assert dispatcher is client.dispatch83 else:84 assert isinstance(dispatcher, httpx.HTTPProxy)84 assert dispatcher.proxy_url == expected858687def test_unsupported_proxy_scheme():
2 unmodified lines
modified:tests/dispatch/test_proxy_http.py+7 added-6 removed
1import pytest23import httpx4from httpx.dispatch.proxy_http import HTTPProxy56from .utils import MockRawSocketBackend78
12 unmodified lines
21 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 lines
57 ),58 )5960 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 lines
107 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 lines
157 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 lines
186 assert b"override: 1" in recv[1]187188189def 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")191192 assert proxy.proxy_url == "http://example.com:1080"193 assert proxy.proxy_headers["Proxy-Authorization"] == "Basic dXNlcjpwYXNzd29yZA=="194195196def 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 lines
modified:tests/models/test_requests.py+14 added-7 removed
16 unmodified lines
17 request = httpx.Request("POST", "http://example.org", data=b"test 123")18 assert request.headers["Content-Length"] == "8"192021@pytest.mark.asyncio22async def test_url_encoded_data():21def test_url_encoded_data():22 request = httpx.Request("POST", "http://example.org", data={"test": "123"})24 await request.aread()23 request.read()2425 assert request.headers["Content-Type"] == "application/x-www-form-urlencoded"26 assert request.content == b"test=123"272830@pytest.mark.asyncio31async def test_json_encoded_data():29def test_json_encoded_data():30 request = httpx.Request("POST", "http://example.org", json={"test": 123})33 await request.aread()31 request.read()3233 assert request.headers["Content-Type"] == "application/json"34 assert request.content == b'{"test": 123}'353637def 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.content444546@pytest.mark.asyncio40async def test_read_and_stream_data():47async 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 lines
modified:tests/test_api.py+20 added-29 removed
1 unmodified line
23import httpx456@pytest.mark.asyncio7async def test_get(server):8 response = await httpx.get(server.url)6def 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"121315@pytest.mark.asyncio16async def test_post(server):17 response = await httpx.post(server.url, data=b"Hello, world!")14def test_post(server):15 response = httpx.post(server.url, data=b"Hello, world!")16 assert response.status_code == 20017 assert response.reason_phrase == "OK"181922@pytest.mark.asyncio23async def test_post_byte_iterator(server):24 async def data():20def test_post_byte_iterator(server):21 def data():22 yield b"Hello"23 yield b", "24 yield b"world!"2529 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"293034@pytest.mark.asyncio35async def test_options(server):36 response = await httpx.options(server.url)31def test_options(server):32 response = httpx.options(server.url)33 assert response.status_code == 20034 assert response.reason_phrase == "OK"353641@pytest.mark.asyncio42async def test_head(server):43 response = await httpx.head(server.url)37def test_head(server):38 response = httpx.head(server.url)39 assert response.status_code == 20040 assert response.reason_phrase == "OK"414248@pytest.mark.asyncio49async def test_put(server):50 response = await httpx.put(server.url, data=b"Hello, world!")43def test_put(server):44 response = httpx.put(server.url, data=b"Hello, world!")45 assert response.status_code == 20046 assert response.reason_phrase == "OK"474855@pytest.mark.asyncio56async def test_patch(server):57 response = await httpx.patch(server.url, data=b"Hello, world!")49def test_patch(server):50 response = httpx.patch(server.url, data=b"Hello, world!")51 assert response.status_code == 20052 assert response.reason_phrase == "OK"535462@pytest.mark.asyncio63async def test_delete(server):64 response = await httpx.delete(server.url)55def test_delete(server):56 response = httpx.delete(server.url)57 assert response.status_code == 20058 assert response.reason_phrase == "OK"596069@pytest.mark.asyncio70async def test_stream(server):71 async with httpx.stream("GET", server.url) as response:72 await response.aread()61def test_stream(server):62 with httpx.stream("GET", server.url) as response:63 response.read()6465 assert response.status_code == 20066 assert response.reason_phrase == "OK"67 assert response.text == "Hello, world!"
7 unmodified lines
added:tests/test_wsgi.py+95 added
1import sys23import pytest45import httpx678def hello_world(environ, start_response):9 status = "200 OK"10 output = b"Hello, World!"1112 response_headers = [13 ("Content-type", "text/plain"),14 ("Content-Length", str(len(output))),15 ]1617 start_response(status, response_headers)1819 return [output]202122def echo_body(environ, start_response):23 status = "200 OK"24 output = environ["wsgi.input"].read()2526 response_headers = [27 ("Content-type", "text/plain"),28 ("Content-Length", str(len(output))),29 ]3031 start_response(status, response_headers)3233 return [output]343536def echo_body_with_response_stream(environ, start_response):37 status = "200 OK"3839 response_headers = [("Content-Type", "text/plain")]4041 start_response(status, response_headers)4243 def output_generator(f):44 while True:45 output = f.read(2)46 if not output:47 break48 yield output4950 return output_generator(f=environ["wsgi.input"])515253def raise_exc(environ, start_response):54 status = "500 Server Error"55 output = b"Nope!"5657 response_headers = [58 ("Content-type", "text/plain"),59 ("Content-Length", str(len(output))),60 ]6162 try:63 raise ValueError()64 except ValueError:65 exc_info = sys.exc_info()66 start_response(status, response_headers, exc_info=exc_info)6768 return [output]697071def 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!"767778def 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"838485def 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"909192def 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 lines
13combine_as_imports = True14force_grid_wrap = 015include_trailing_comma = True16known_first_party = httpx,tests17known_third_party = brotli,certifi,chardet,cryptography,h11,h2,hstspreload,pytest,rfc3986,setuptools,sniffio,trio,trustme,uvicorn17known_third_party = brotli,certifi,chardet,cryptography,h11,h2,hstspreload,pytest,rfc3986,setuptools,sniffio,trio,trustme,urllib3,uvicorn18line_length = 8819multi_line_output = 32021[tool:pytest]
3 unmodified lines
modified:setup.py+1 added
57 unmodified lines
58 "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