Skip to content
Myr

Httpcore interface (#804)

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

* First pass as switching dispatchers over to httpcore interface * Updates for httpcore interface * headers in dispatch API as plain list of bytes * Integrate against httpcore 0.6 * Integrate against httpcore interface * Drop UDS, since not supported by httpcore * Fix base class for mock dispatchers in tests * Merge master and mark as potential '0.13.dev0' release

authored by Tom Christie · committed by GitHub · parent 631ba97 · Browse files · 35 files+561 added−2457 removed
This commit

State

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

Diff stats

35 files+561 added−2457 removed

  • tests:+283 added−1121 removed
  • other:+278 added−1336 removed

35 files+561 added−2457 removed

modified:httpx/_dispatch/asgi.py+32 added-27 removed
1import typing1from typing import Callable, Dict, List, Optional, Tuple23from .._config import TimeoutTypes3import httpcore45from .._content_streams import ByteStream5from .._models import Request, Response6from .base import AsyncDispatcher679class ASGIDispatch(AsyncDispatcher):8class ASGIDispatch(httpcore.AsyncHTTPTransport):9 """10 A custom AsyncDispatcher that handles sending requests directly to an ASGI app.11 The simplest way to use this functionality is to use the `app` argument.12
26 unmodified lines
39 """4041 def __init__(42 self,44 app: typing.Callable,43 app: Callable,44 raise_app_exceptions: bool = True,45 root_path: str = "",47 client: typing.Tuple[str, int] = ("127.0.0.1", 123),46 client: Tuple[str, int] = ("127.0.0.1", 123),47 ) -> None:48 self.app = app49 self.raise_app_exceptions = raise_app_exceptions50 self.root_path = root_path51 self.client = client5254 async def send(self, request: Request, timeout: TimeoutTypes = None) -> Response:53 async def request(54 self,55 method: bytes,56 url: Tuple[bytes, bytes, int, bytes],57 headers: List[Tuple[bytes, bytes]] = None,58 stream: httpcore.AsyncByteStream = None,59 timeout: Dict[str, Optional[float]] = None,60 ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream]:61 scheme, host, port, full_path = url62 path, _, query = full_path.partition(b"?")63 scope = {64 "type": "http",65 "asgi": {"version": "3.0"},66 "http_version": "1.1",59 "method": request.method,60 "headers": request.headers.raw,61 "scheme": request.url.scheme,62 "path": request.url.path,63 "query_string": request.url.query.encode("ascii"),64 "server": request.url.host,67 "method": method.decode(),68 "headers": headers,69 "scheme": scheme.decode("ascii"),70 "path": path.decode("ascii"),71 "query_string": query,72 "server": (host.decode("ascii"), port),73 "client": self.client,74 "root_path": self.root_path,75 }76 status_code = None69 headers = None77 response_headers = None78 body_parts = []79 response_started = False80 response_complete = False8174 request_body_chunks = request.stream.__aiter__()82 headers = [] if headers is None else headers83 stream = ByteStream(b"") if stream is None else stream8485 request_body_chunks = stream.__aiter__()8687 async def receive() -> dict:88 try:89 body = await request_body_chunks.__anext__()90 except StopAsyncIteration:91 return {"type": "http.request", "body": b"", "more_body": False}92 return {"type": "http.request", "body": body, "more_body": True}9394 async def send(message: dict) -> None:84 nonlocal status_code, headers, body_parts95 nonlocal status_code, response_headers, body_parts96 nonlocal response_started, response_complete9798 if message["type"] == "http.response.start":99 assert not response_started100101 status_code = message["status"]91 headers = message.get("headers", [])102 response_headers = message.get("headers", [])103 response_started = True104105 elif message["type"] == "http.response.body":106 assert not response_complete107 body = message.get("body", b"")108 more_body = message.get("more_body", False)10999 if body and request.method != "HEAD":110 if body and method != b"HEAD":111 body_parts.append(body)112113 if not more_body:114 response_complete = True
5 unmodified lines
120 raise121122 assert response_complete123 assert status_code is not None113 assert headers is not None124 assert response_headers is not None125126 stream = ByteStream(b"".join(body_parts))127117 return Response(118 status_code=status_code,119 http_version="HTTP/1.1",120 headers=headers,121 stream=stream,122 request=request,123 )128 return (b"HTTP/1.1", status_code, b"", response_headers, stream)
deleted:httpx/_dispatch/base.py-64 removed
1import typing2from types import TracebackType34from .._config import Timeout5from .._models import (6 HeaderTypes,7 QueryParamTypes,8 Request,9 RequestData,10 Response,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.3031 Stubs out the interface, as well as providing a `.request()` convenience32 implementation, to make it easy to use or test stand-alone AsyncDispatchers,33 without requiring a complete `AsyncClient` instance.34 """3536 async def request(37 self,38 method: str,39 url: URLTypes,40 *,41 data: RequestData = b"",42 params: QueryParamTypes = None,43 headers: HeaderTypes = None,44 timeout: Timeout = None,45 ) -> Response:46 request = Request(method, url, data=data, params=params, headers=headers)47 return await self.send(request, timeout=timeout)4849 async def send(self, request: Request, timeout: Timeout = None) -> Response:50 raise NotImplementedError() # pragma: nocover5152 async def close(self) -> None:53 pass # pragma: nocover5455 async def __aenter__(self) -> "AsyncDispatcher":56 return self5758 async def __aexit__(59 self,60 exc_type: typing.Type[BaseException] = None,61 exc_value: BaseException = None,62 traceback: TracebackType = None,63 ) -> None:64 await self.close()
deleted:httpx/_dispatch/connection_pool.py-221 removed
1import typing23from .._backends.base import BaseSemaphore, ConcurrencyBackend, lookup_backend4from .._config import (5 DEFAULT_POOL_LIMITS,6 CertTypes,7 PoolLimits,8 SSLConfig,9 Timeout,10 VerifyTypes,11)12from .._exceptions import PoolTimeout13from .._models import Origin, Request, Response14from .._utils import get_logger15from .base import AsyncDispatcher16from .connection import HTTPConnection1718CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]192021logger = get_logger(__name__)222324class NullSemaphore(BaseSemaphore):25 async def acquire(self, timeout: float = None) -> None:26 return2728 def release(self) -> None:29 return303132class ConnectionStore:33 """34 We need to maintain collections of connections in a way that allows us to:3536 * Lookup connections by origin.37 * Iterate over connections by insertion time.38 * Return the total number of connections.39 """4041 def __init__(self) -> None:42 self.all: typing.Dict[HTTPConnection, float] = {}43 self.by_origin: typing.Dict[Origin, typing.Dict[HTTPConnection, float]] = {}4445 def pop_by_origin(46 self, origin: Origin, http2_only: bool = False47 ) -> typing.Optional[HTTPConnection]:48 try:49 connections = self.by_origin[origin]50 except KeyError:51 return None5253 connection = next(reversed(list(connections.keys())))54 if http2_only and not connection.is_http2:55 return None5657 del connections[connection]58 if not connections:59 del self.by_origin[origin]60 del self.all[connection]6162 return connection6364 def add(self, connection: HTTPConnection) -> None:65 self.all[connection] = 0.066 try:67 self.by_origin[connection.origin][connection] = 0.068 except KeyError:69 self.by_origin[connection.origin] = {connection: 0.0}7071 def remove(self, connection: HTTPConnection) -> None:72 del self.all[connection]73 del self.by_origin[connection.origin][connection]74 if not self.by_origin[connection.origin]:75 del self.by_origin[connection.origin]7677 def clear(self) -> None:78 self.all.clear()79 self.by_origin.clear()8081 def __iter__(self) -> typing.Iterator[HTTPConnection]:82 return iter(self.all.keys())8384 def __len__(self) -> int:85 return len(self.all)868788class ConnectionPool(AsyncDispatcher):89 KEEP_ALIVE_EXPIRY = 5.09091 def __init__(92 self,93 *,94 verify: VerifyTypes = True,95 cert: CertTypes = None,96 trust_env: bool = None,97 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,98 http2: bool = False,99 backend: typing.Union[str, ConcurrencyBackend] = "auto",100 uds: typing.Optional[str] = None,101 ):102 self.ssl = SSLConfig(verify=verify, cert=cert, trust_env=trust_env, http2=http2)103 self.pool_limits = pool_limits104 self.is_closed = False105 self.uds = uds106107 self.keepalive_connections = ConnectionStore()108 self.active_connections = ConnectionStore()109110 self.backend = lookup_backend(backend)111 self.next_keepalive_check = 0.0112113 @property114 def max_connections(self) -> BaseSemaphore:115 # We do this lazily, to make sure backend autodetection always116 # runs within an async context.117 if not hasattr(self, "_max_connections"):118 limit = self.pool_limits.hard_limit119 if limit:120 self._max_connections = self.backend.create_semaphore(121 limit, exc_class=PoolTimeout122 )123 else:124 self._max_connections = NullSemaphore()125126 return self._max_connections127128 @property129 def num_connections(self) -> int:130 return len(self.keepalive_connections) + len(self.active_connections)131132 async def check_keepalive_expiry(self) -> None:133 now = self.backend.time()134 if now < self.next_keepalive_check:135 return136 self.next_keepalive_check = now + 1.0137138 # Iterate through all the keep alive connections.139 # We create a list here to avoid any 'changed during iteration' errors.140 keepalives = list(self.keepalive_connections.all.keys())141 for connection in keepalives:142 if connection.expires_at is not None and now > connection.expires_at:143 self.keepalive_connections.remove(connection)144 self.max_connections.release()145 await connection.close()146147 async def send(self, request: Request, timeout: Timeout = None) -> Response:148 await self.check_keepalive_expiry()149 connection = await self.acquire_connection(150 origin=Origin(request.url), timeout=timeout151 )152 try:153 response = await connection.send(request, timeout=timeout)154 except BaseException as exc:155 self.active_connections.remove(connection)156 self.max_connections.release()157 raise exc158159 return response160161 async def acquire_connection(162 self, origin: Origin, timeout: Timeout = None163 ) -> HTTPConnection:164 logger.trace(f"acquire_connection origin={origin!r}")165 connection = self.pop_connection(origin)166167 if connection is None:168 pool_timeout = None if timeout is None else timeout.pool_timeout169170 await self.max_connections.acquire(timeout=pool_timeout)171 connection = HTTPConnection(172 origin,173 ssl=self.ssl,174 backend=self.backend,175 release_func=self.release_connection,176 uds=self.uds,177 )178 logger.trace(f"new_connection connection={connection!r}")179 else:180 logger.trace(f"reuse_connection connection={connection!r}")181182 self.active_connections.add(connection)183184 return connection185186 async def release_connection(self, connection: HTTPConnection) -> None:187 logger.trace(f"release_connection connection={connection!r}")188 if connection.is_closed:189 self.active_connections.remove(connection)190 self.max_connections.release()191 elif (192 self.pool_limits.soft_limit is not None193 and self.num_connections > self.pool_limits.soft_limit194 ):195 self.active_connections.remove(connection)196 self.max_connections.release()197 await connection.close()198 else:199 now = self.backend.time()200 connection.expires_at = now + self.KEEP_ALIVE_EXPIRY201 self.active_connections.remove(connection)202 self.keepalive_connections.add(connection)203204 async def close(self) -> None:205 self.is_closed = True206 connections = list(self.keepalive_connections)207 self.keepalive_connections.clear()208 for connection in connections:209 self.max_connections.release()210 await connection.close()211212 def pop_connection(self, origin: Origin) -> typing.Optional[HTTPConnection]:213 connection = self.active_connections.pop_by_origin(origin, http2_only=True)214 if connection is None:215 connection = self.keepalive_connections.pop_by_origin(origin)216217 if connection is not None and connection.is_connection_dropped():218 self.max_connections.release()219 connection = None220221 return connection
deleted:httpx/_dispatch/connection.py-149 removed
1import functools2import typing34import h1156from .._backends.base import ConcurrencyBackend, lookup_backend7from .._config import SSLConfig, Timeout8from .._models import URL, Origin, Request, Response9from .._utils import get_logger10from .base import AsyncDispatcher11from .http2 import HTTP2Connection12from .http11 import HTTP11Connection1314# Callback signature: async def callback(conn: HTTPConnection) -> None15ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]161718logger = get_logger(__name__)192021class HTTPConnection(AsyncDispatcher):22 def __init__(23 self,24 origin: typing.Union[str, Origin],25 ssl: SSLConfig = None,26 backend: typing.Union[str, ConcurrencyBackend] = "auto",27 release_func: typing.Optional[ReleaseCallback] = None,28 uds: typing.Optional[str] = None,29 ):30 self.origin = Origin(origin) if isinstance(origin, str) else origin31 self.ssl = SSLConfig() if ssl is None else ssl32 self.backend = lookup_backend(backend)33 self.release_func = release_func34 self.uds = uds35 self.connection: typing.Union[None, HTTP11Connection, HTTP2Connection] = None36 self.expires_at: typing.Optional[float] = None3738 async def send(self, request: Request, timeout: Timeout = None) -> Response:39 timeout = Timeout() if timeout is None else timeout4041 if self.connection is None:42 self.connection = await self.connect(timeout=timeout)4344 return await self.connection.send(request, timeout=timeout)4546 async def connect(47 self, timeout: Timeout48 ) -> typing.Union[HTTP11Connection, HTTP2Connection]:49 host = self.origin.host50 port = self.origin.port51 ssl_context = None if not self.origin.is_ssl else self.ssl.ssl_context5253 if self.release_func is None:54 on_release = None55 else:56 on_release = functools.partial(self.release_func, self)5758 if self.uds is None:59 logger.trace(60 f"start_connect tcp host={host!r} port={port!r} timeout={timeout!r}"61 )62 socket = await self.backend.open_tcp_stream(63 host, port, ssl_context, timeout64 )65 else:66 logger.trace(67 f"start_connect uds path={self.uds!r} host={host!r} timeout={timeout!r}"68 )69 socket = await self.backend.open_uds_stream(70 self.uds, host, ssl_context, timeout71 )7273 http_version = socket.get_http_version()74 logger.trace(f"connected http_version={http_version!r}")7576 if http_version == "HTTP/2":77 return HTTP2Connection(socket, self.backend, on_release=on_release)78 return HTTP11Connection(socket, on_release=on_release)7980 async def tunnel_start_tls(81 self, origin: Origin, proxy_url: URL, timeout: Timeout = None,82 ) -> None:83 """84 Upgrade this connection to use TLS, assuming it represents a TCP tunnel.85 """86 timeout = Timeout() if timeout is None else timeout8788 # First, check that we are in the correct state to start TLS, i.e. we've89 # just agreed to switch protocols with the server via HTTP/1.1.90 assert isinstance(self.connection, HTTP11Connection)91 h11_connection = self.connection92 assert h11_connection is not None93 assert h11_connection.h11_state.our_state == h11.SWITCHED_PROTOCOL9495 # Store this information here so that we can transfer96 # it to the new internal connection object after97 # the old one goes to 'SWITCHED_PROTOCOL'.98 # Note that the negotiated 'http_version' may change after the TLS upgrade.99 http_version = "HTTP/1.1"100 socket = h11_connection.socket101 on_release = h11_connection.on_release102103 if origin.is_ssl:104 # Pull the socket stream off the internal HTTP connection object,105 # and run start_tls().106 ssl_context = self.ssl.ssl_context107108 logger.trace(f"tunnel_start_tls proxy_url={proxy_url!r} origin={origin!r}")109 socket = await socket.start_tls(110 hostname=origin.host, ssl_context=ssl_context, timeout=timeout111 )112 http_version = socket.get_http_version()113 logger.trace(114 f"tunnel_tls_complete "115 f"proxy_url={proxy_url!r} "116 f"origin={origin!r} "117 f"http_version={http_version!r}"118 )119 else:120 # User requested the use of a tunnel, but they're performing a plain-text121 # HTTP request. Don't try to upgrade to TLS in this case.122 pass123124 if http_version == "HTTP/2":125 self.connection = HTTP2Connection(126 socket, self.backend, on_release=on_release127 )128 else:129 self.connection = HTTP11Connection(socket, on_release=on_release)130131 async def close(self) -> None:132 logger.trace("close_connection")133 if self.connection is not None:134 await self.connection.close()135136 @property137 def is_http2(self) -> bool:138 return self.connection is not None and self.connection.is_http2139140 @property141 def is_closed(self) -> bool:142 return self.connection is not None and self.connection.is_closed143144 def is_connection_dropped(self) -> bool:145 return self.connection is not None and self.connection.is_connection_dropped()146147 def __repr__(self) -> str:148 class_name = self.__class__.__name__149 return f"{class_name}(origin={self.origin!r})"
deleted:httpx/_dispatch/http11.py-206 removed
1import typing23import h1145from .._backends.base import BaseSocketStream6from .._config import Timeout7from .._content_streams import AsyncIteratorStream8from .._exceptions import ConnectionClosed, ProtocolError9from .._models import Request, Response10from .._utils import get_logger1112H11Event = typing.Union[13 h11.Request,14 h11.Response,15 h11.InformationalResponse,16 h11.Data,17 h11.EndOfMessage,18 h11.ConnectionClosed,19]202122# Callback signature: async def callback() -> None23# In practice the callback will be a functools partial, which binds24# the `ConnectionPool.release_connection(conn: HTTPConnection)` method.25OnReleaseCallback = typing.Callable[[], typing.Awaitable[None]]262728logger = get_logger(__name__)293031class HTTP11Connection:32 READ_NUM_BYTES = 40963334 def __init__(35 self,36 socket: BaseSocketStream,37 on_release: typing.Optional[OnReleaseCallback] = None,38 ):39 self.socket = socket40 self.on_release = on_release41 self.h11_state = h11.Connection(our_role=h11.CLIENT)4243 @property44 def is_http2(self) -> bool:45 return False4647 async def send(self, request: Request, timeout: Timeout = None) -> Response:48 timeout = Timeout() if timeout is None else timeout4950 await self._send_request(request, timeout)51 await self._send_request_body(request, timeout)52 http_version, status_code, headers = await self._receive_response(timeout)53 stream = AsyncIteratorStream(54 aiterator=self._receive_response_data(timeout),55 close_func=self.response_closed,56 )5758 return Response(59 status_code=status_code,60 http_version=http_version,61 headers=headers,62 stream=stream,63 request=request,64 )6566 async def close(self) -> None:67 event = h11.ConnectionClosed()68 try:69 logger.trace(f"send_event event={event!r}")70 self.h11_state.send(event)71 except h11.LocalProtocolError: # pragma: no cover72 # Premature client disconnect73 pass74 await self.socket.close()7576 async def _send_request(self, request: Request, timeout: Timeout) -> None:77 """78 Send the request method, URL, and headers to the network.79 """80 logger.trace(81 f"send_headers method={request.method!r} "82 f"target={request.url.full_path!r} "83 f"headers={request.headers!r}"84 )8586 method = request.method.encode("ascii")87 target = request.url.full_path.encode("ascii")88 headers = request.headers.raw89 event = h11.Request(method=method, target=target, headers=headers)90 await self._send_event(event, timeout)9192 async def _send_request_body(self, request: Request, timeout: Timeout) -> None:93 """94 Send the request body to the network.95 """96 try:97 # Send the request body.98 async for chunk in request.stream:99 logger.trace(f"send_data data=Data(<{len(chunk)} bytes>)")100 event = h11.Data(data=chunk)101 await self._send_event(event, timeout)102103 # Finalize sending the request.104 event = h11.EndOfMessage()105 await self._send_event(event, timeout)106 except OSError: # pragma: nocover107 # Once we've sent the initial part of the request we don't actually108 # care about connection errors that occur when sending the body.109 # Ignore these, and defer to any exceptions on reading the response.110 self.h11_state.send_failed()111112 async def _send_event(self, event: H11Event, timeout: Timeout) -> None:113 """114 Send a single `h11` event to the network, waiting for the data to115 drain before returning.116 """117 bytes_to_send = self.h11_state.send(event)118 await self.socket.write(bytes_to_send, timeout)119120 async def _receive_response(121 self, timeout: Timeout122 ) -> typing.Tuple[str, int, typing.List[typing.Tuple[bytes, bytes]]]:123 """124 Read the response status and headers from the network.125 """126 while True:127 event = await self._receive_event(timeout)128 if isinstance(event, h11.InformationalResponse):129 continue130 else:131 assert isinstance(event, h11.Response)132 break # pragma: no cover133 http_version = "HTTP/%s" % event.http_version.decode("latin-1", errors="ignore")134 return http_version, event.status_code, event.headers135136 async def _receive_response_data(137 self, timeout: Timeout138 ) -> typing.AsyncIterator[bytes]:139 """140 Read the response data from the network.141 """142 while True:143 event = await self._receive_event(timeout)144 if isinstance(event, h11.Data):145 yield bytes(event.data)146 else:147 assert isinstance(event, h11.EndOfMessage) or event is h11.PAUSED148 break # pragma: no cover149150 async def _receive_event(self, timeout: Timeout) -> H11Event:151 """152 Read a single `h11` event, reading more data from the network if needed.153 """154 while True:155 try:156 event = self.h11_state.next_event()157 except h11.RemoteProtocolError as e:158 logger.debug(159 "h11.RemoteProtocolError exception "160 + f"their_state={self.h11_state.their_state} "161 + f"error_status_hint={e.error_status_hint}"162 )163 if self.socket.is_connection_dropped():164 raise ConnectionClosed(e)165 raise ProtocolError(e)166167 if isinstance(event, h11.Data):168 logger.trace(f"receive_event event=Data(<{len(event.data)} bytes>)")169 else:170 logger.trace(f"receive_event event={event!r}")171172 if event is h11.NEED_DATA:173 try:174 data = await self.socket.read(self.READ_NUM_BYTES, timeout)175 except OSError: # pragma: nocover176 data = b""177 self.h11_state.receive_data(data)178 else:179 assert event is not h11.NEED_DATA180 break # pragma: no cover181 return event182183 async def response_closed(self) -> None:184 logger.trace(185 f"response_closed "186 f"our_state={self.h11_state.our_state!r} "187 f"their_state={self.h11_state.their_state}"188 )189 if (190 self.h11_state.our_state is h11.DONE191 and self.h11_state.their_state is h11.DONE192 ):193 # Get ready for another request/response cycle.194 self.h11_state.start_next_cycle()195 else:196 await self.close()197198 if self.on_release is not None:199 await self.on_release()200201 @property202 def is_closed(self) -> bool:203 return self.h11_state.our_state in (h11.CLOSED, h11.ERROR)204205 def is_connection_dropped(self) -> bool:206 return self.socket.is_connection_dropped()
deleted:httpx/_dispatch/http2.py-298 removed
1import typing23import h2.connection4import h2.events5from h2.config import H2Configuration6from h2.settings import SettingCodes, Settings78from .._backends.base import (9 BaseLock,10 BaseSocketStream,11 ConcurrencyBackend,12 lookup_backend,13)14from .._config import Timeout15from .._content_streams import AsyncIteratorStream16from .._exceptions import ProtocolError17from .._models import Request, Response18from .._utils import get_logger1920logger = get_logger(__name__)212223class HTTP2Connection:24 READ_NUM_BYTES = 409625 CONFIG = H2Configuration(validate_inbound_headers=False)2627 def __init__(28 self,29 socket: BaseSocketStream,30 backend: typing.Union[str, ConcurrencyBackend] = "auto",31 on_release: typing.Callable = None,32 ):33 self.socket = socket34 self.backend = lookup_backend(backend)35 self.on_release = on_release36 self.state = h2.connection.H2Connection(config=self.CONFIG)3738 self.streams = {} # type: typing.Dict[int, HTTP2Stream]39 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]4041 self.sent_connection_init = False4243 @property44 def is_http2(self) -> bool:45 return True4647 @property48 def init_lock(self) -> BaseLock:49 # We do this lazily, to make sure backend autodetection always50 # runs within an async context.51 if not hasattr(self, "_initialization_lock"):52 self._initialization_lock = self.backend.create_lock()53 return self._initialization_lock5455 async def send(self, request: Request, timeout: Timeout = None) -> Response:56 timeout = Timeout() if timeout is None else timeout5758 async with self.init_lock:59 if not self.sent_connection_init:60 # The very first stream is responsible for initiating the connection.61 await self.send_connection_init(timeout)62 self.sent_connection_init = True63 stream_id = self.state.get_next_available_stream_id()6465 stream = HTTP2Stream(stream_id=stream_id, connection=self)66 self.streams[stream_id] = stream67 self.events[stream_id] = []68 return await stream.send(request, timeout)6970 async def send_connection_init(self, timeout: Timeout) -> None:71 """72 The HTTP/2 connection requires some initial setup before we can start73 using individual request/response streams on it.74 """7576 # Need to set these manually here instead of manipulating via77 # __setitem__() otherwise the H2Connection will emit SettingsUpdate78 # frames in addition to sending the undesired defaults.79 self.state.local_settings = Settings(80 client=True,81 initial_values={82 # Disable PUSH_PROMISE frames from the server since we don't do anything83 # with them for now. Maybe when we support caching?84 SettingCodes.ENABLE_PUSH: 0,85 # These two are taken from h2 for safe defaults86 SettingCodes.MAX_CONCURRENT_STREAMS: 100,87 SettingCodes.MAX_HEADER_LIST_SIZE: 65536,88 },89 )9091 # Some websites (*cough* Yahoo *cough*) balk at this setting being92 # present in the initial handshake since it's not defined in the original93 # RFC despite the RFC mandating ignoring settings you don't know about.94 del self.state.local_settings[h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL]9596 self.state.initiate_connection()97 self.state.increment_flow_control_window(2 ** 24)98 data_to_send = self.state.data_to_send()99 await self.socket.write(data_to_send, timeout)100101 @property102 def is_closed(self) -> bool:103 return False104105 def is_connection_dropped(self) -> bool:106 return self.socket.is_connection_dropped()107108 async def close(self) -> None:109 await self.socket.close()110111 async def wait_for_outgoing_flow(self, stream_id: int, timeout: Timeout) -> int:112 """113 Returns the maximum allowable outgoing flow for a given stream.114115 If the allowable flow is zero, then waits on the network until116 WindowUpdated frames have increased the flow rate.117118 https://tools.ietf.org/html/rfc7540#section-6.9119 """120 local_flow = self.state.local_flow_control_window(stream_id)121 connection_flow = self.state.max_outbound_frame_size122 flow = min(local_flow, connection_flow)123 while flow == 0:124 await self.receive_events(timeout)125 local_flow = self.state.local_flow_control_window(stream_id)126 connection_flow = self.state.max_outbound_frame_size127 flow = min(local_flow, connection_flow)128 return flow129130 async def wait_for_event(self, stream_id: int, timeout: Timeout) -> h2.events.Event:131 """132 Returns the next event for a given stream.133134 If no events are available yet, then waits on the network until135 an event is available.136 """137 while not self.events[stream_id]:138 await self.receive_events(timeout)139 return self.events[stream_id].pop(0)140141 async def receive_events(self, timeout: Timeout) -> None:142 """143 Read some data from the network, and update the H2 state.144 """145 data = await self.socket.read(self.READ_NUM_BYTES, timeout)146 events = self.state.receive_data(data)147 for event in events:148 event_stream_id = getattr(event, "stream_id", 0)149 logger.trace(f"receive_event stream_id={event_stream_id} event={event!r}")150151 if hasattr(event, "error_code"):152 raise ProtocolError(event)153154 if event_stream_id in self.events:155 self.events[event_stream_id].append(event)156157 data_to_send = self.state.data_to_send()158 await self.socket.write(data_to_send, timeout)159160 async def send_headers(161 self,162 stream_id: int,163 headers: typing.List[typing.Tuple[bytes, bytes]],164 end_stream: bool,165 timeout: Timeout,166 ) -> None:167 self.state.send_headers(stream_id, headers, end_stream=end_stream)168 self.state.increment_flow_control_window(2 ** 24, stream_id=stream_id)169 data_to_send = self.state.data_to_send()170 await self.socket.write(data_to_send, timeout)171172 async def send_data(self, stream_id: int, chunk: bytes, timeout: Timeout) -> None:173 self.state.send_data(stream_id, chunk)174 data_to_send = self.state.data_to_send()175 await self.socket.write(data_to_send, timeout)176177 async def end_stream(self, stream_id: int, timeout: Timeout) -> None:178 self.state.end_stream(stream_id)179 data_to_send = self.state.data_to_send()180 await self.socket.write(data_to_send, timeout)181182 async def acknowledge_received_data(183 self, stream_id: int, amount: int, timeout: Timeout184 ) -> None:185 self.state.acknowledge_received_data(amount, stream_id)186 data_to_send = self.state.data_to_send()187 await self.socket.write(data_to_send, timeout)188189 async def close_stream(self, stream_id: int) -> None:190 del self.streams[stream_id]191 del self.events[stream_id]192193 if not self.streams and self.on_release is not None:194 await self.on_release()195196197class HTTP2Stream:198 def __init__(self, stream_id: int, connection: HTTP2Connection) -> None:199 self.stream_id = stream_id200 self.connection = connection201202 async def send(self, request: Request, timeout: Timeout) -> Response:203 # Send the request.204 has_body = (205 "Content-Length" in request.headers206 or "Transfer-Encoding" in request.headers207 )208209 await self.send_headers(request, has_body, timeout)210 if has_body:211 await self.send_body(request, timeout)212213 # Receive the response.214 status_code, headers = await self.receive_response(timeout)215 stream = AsyncIteratorStream(216 aiterator=self.body_iter(timeout), close_func=self.close217 )218219 return Response(220 status_code=status_code,221 http_version="HTTP/2",222 headers=headers,223 stream=stream,224 request=request,225 )226227 async def send_headers(228 self, request: Request, has_body: bool, timeout: Timeout229 ) -> None:230 headers = [231 (b":method", request.method.encode("ascii")),232 (b":authority", request.url.authority.encode("ascii")),233 (b":scheme", request.url.scheme.encode("ascii")),234 (b":path", request.url.full_path.encode("ascii")),235 ] + [236 (k, v)237 for k, v in request.headers.raw238 if k not in (b"host", b"transfer-encoding")239 ]240 end_stream = not has_body241242 logger.trace(243 f"send_headers "244 f"stream_id={self.stream_id} "245 f"method={request.method!r} "246 f"target={request.url.full_path!r} "247 f"headers={headers!r}"248 )249 await self.connection.send_headers(self.stream_id, headers, end_stream, timeout)250251 async def send_body(self, request: Request, timeout: Timeout) -> None:252 logger.trace(f"send_body stream_id={self.stream_id}")253 async for data in request.stream:254 while data:255 max_flow = await self.connection.wait_for_outgoing_flow(256 self.stream_id, timeout257 )258 chunk_size = min(len(data), max_flow)259 chunk, data = data[:chunk_size], data[chunk_size:]260 await self.connection.send_data(self.stream_id, chunk, timeout)261262 await self.connection.end_stream(self.stream_id, timeout)263264 async def receive_response(265 self, timeout: Timeout266 ) -> typing.Tuple[int, typing.List[typing.Tuple[bytes, bytes]]]:267 """268 Read the response status and headers from the network.269 """270 while True:271 event = await self.connection.wait_for_event(self.stream_id, timeout)272 if isinstance(event, h2.events.ResponseReceived):273 break274275 status_code = 200276 headers = []277 for k, v in event.headers:278 if k == b":status":279 status_code = int(v.decode("ascii", errors="ignore"))280 elif not k.startswith(b":"):281 headers.append((k, v))282283 return (status_code, headers)284285 async def body_iter(self, timeout: Timeout) -> typing.AsyncIterator[bytes]:286 while True:287 event = await self.connection.wait_for_event(self.stream_id, timeout)288 if isinstance(event, h2.events.DataReceived):289 amount = event.flow_controlled_length290 await self.connection.acknowledge_received_data(291 self.stream_id, amount, timeout292 )293 yield event.data294 elif isinstance(event, (h2.events.StreamEnded, h2.events.StreamReset)):295 break296297 async def close(self) -> None:298 await self.connection.close_stream(self.stream_id)
deleted:httpx/_dispatch/proxy_http.py-208 removed
1import enum2import typing3import warnings4from base64 import b64encode56from .._backends.base import ConcurrencyBackend7from .._config import (8 DEFAULT_POOL_LIMITS,9 CertTypes,10 PoolLimits,11 SSLConfig,12 Timeout,13 VerifyTypes,14)15from .._exceptions import ProxyError16from .._models import URL, Headers, HeaderTypes, Origin, Request, Response, URLTypes17from .._utils import get_logger18from .connection import HTTPConnection19from .connection_pool import ConnectionPool2021logger = get_logger(__name__)222324class HTTPProxyMode(enum.Enum):25 # This enum is pending deprecation in order to reduce API surface area,26 # but is currently still around for 0.8 backwards compat.27 DEFAULT = "DEFAULT"28 FORWARD_ONLY = "FORWARD_ONLY"29 TUNNEL_ONLY = "TUNNEL_ONLY"303132DEFAULT_MODE = "DEFAULT"33FORWARD_ONLY = "FORWARD_ONLY"34TUNNEL_ONLY = "TUNNEL_ONLY"353637class HTTPProxy(ConnectionPool):38 """A proxy that sends requests to the recipient server39 on behalf of the connecting client.40 """4142 def __init__(43 self,44 proxy_url: URLTypes,45 *,46 proxy_headers: HeaderTypes = None,47 proxy_mode: str = "DEFAULT",48 verify: VerifyTypes = True,49 cert: CertTypes = None,50 trust_env: bool = None,51 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,52 http2: bool = False,53 backend: typing.Union[str, ConcurrencyBackend] = "auto",54 ):5556 if isinstance(proxy_mode, HTTPProxyMode): # pragma: nocover57 warnings.warn(58 "The 'HTTPProxyMode' enum is pending deprecation. "59 "Use a plain string instead. proxy_mode='FORWARD_ONLY', or "60 "proxy_mode='TUNNEL_ONLY'."61 )62 proxy_mode = proxy_mode.value63 assert proxy_mode in ("DEFAULT", "FORWARD_ONLY", "TUNNEL_ONLY")6465 self.tunnel_ssl = SSLConfig(66 verify=verify, cert=cert, trust_env=trust_env, http2=False67 )6869 super(HTTPProxy, self).__init__(70 verify=verify,71 cert=cert,72 pool_limits=pool_limits,73 backend=backend,74 trust_env=trust_env,75 http2=http2,76 )7778 self.proxy_url = URL(proxy_url)79 self.proxy_mode = proxy_mode80 self.proxy_headers = Headers(proxy_headers)8182 url = self.proxy_url83 if url.username or url.password:84 self.proxy_headers.setdefault(85 "Proxy-Authorization",86 self.build_auth_header(url.username, url.password),87 )88 # Remove userinfo from the URL authority, e.g.:89 # 'username:password@proxy_host:proxy_port' -> 'proxy_host:proxy_port'90 credentials, _, authority = url.authority.rpartition("@")91 self.proxy_url = url.copy_with(authority=authority)9293 def build_auth_header(self, username: str, password: str) -> str:94 userpass = (username.encode("utf-8"), password.encode("utf-8"))95 token = b64encode(b":".join(userpass)).decode().strip()96 return f"Basic {token}"9798 async def acquire_connection(99 self, origin: Origin, timeout: Timeout = None100 ) -> HTTPConnection:101 if self.should_forward_origin(origin):102 logger.trace(103 f"forward_connection proxy_url={self.proxy_url!r} origin={origin!r}"104 )105 return await super().acquire_connection(Origin(self.proxy_url), timeout)106 else:107 logger.trace(108 f"tunnel_connection proxy_url={self.proxy_url!r} origin={origin!r}"109 )110 return await self.tunnel_connection(origin, timeout)111112 async def tunnel_connection(113 self, origin: Origin, timeout: Timeout = None114 ) -> HTTPConnection:115 """Creates a new HTTPConnection via the CONNECT method116 usually reserved for proxying HTTPS connections.117 """118 connection = self.pop_connection(origin)119120 if connection is None:121 connection = await self.request_tunnel_proxy_connection(origin)122123 # After we receive the 2XX response from the proxy that our124 # tunnel is open we switch the connection's origin125 # to the original so the tunnel can be re-used.126 self.active_connections.remove(connection)127 connection.origin = origin128 self.active_connections.add(connection)129130 await connection.tunnel_start_tls(131 origin=origin, proxy_url=self.proxy_url, timeout=timeout,132 )133 else:134 self.active_connections.add(connection)135136 return connection137138 async def request_tunnel_proxy_connection(self, origin: Origin) -> HTTPConnection:139 """Creates an HTTPConnection by setting up a TCP tunnel"""140 proxy_headers = self.proxy_headers.copy()141 proxy_headers.setdefault("Accept", "*/*")142 proxy_request = Request(143 method="CONNECT", url=self.proxy_url.copy_with(), headers=proxy_headers144 )145 proxy_request.url.full_path = f"{origin.host}:{origin.port}"146147 await self.max_connections.acquire()148149 connection = HTTPConnection(150 Origin(self.proxy_url),151 ssl=self.tunnel_ssl,152 backend=self.backend,153 release_func=self.release_connection,154 )155 self.active_connections.add(connection)156157 # See if our tunnel has been opened successfully158 proxy_response = await connection.send(proxy_request)159 logger.trace(160 f"tunnel_response "161 f"proxy_url={self.proxy_url!r} "162 f"origin={origin!r} "163 f"response={proxy_response!r}"164 )165 if not (200 <= proxy_response.status_code <= 299):166 await proxy_response.aread()167 raise ProxyError(168 f"Non-2XX response received from HTTP proxy "169 f"({proxy_response.status_code})",170 request=proxy_request,171 response=proxy_response,172 )173 else:174 # Hack to ingest the response, without closing it.175 async for chunk in proxy_response._raw_stream:176 pass177178 return connection179180 def should_forward_origin(self, origin: Origin) -> bool:181 """Determines if the given origin should182 be forwarded or tunneled. If 'proxy_mode' is 'DEFAULT'183 then the proxy will forward all 'HTTP' requests and184 tunnel all 'HTTPS' requests.185 """186 return (187 self.proxy_mode == DEFAULT_MODE and not origin.is_ssl188 ) or self.proxy_mode == FORWARD_ONLY189190 async def send(self, request: Request, timeout: Timeout = None) -> Response:191 if self.should_forward_origin(Origin(request.url)):192 # Change the request to have the target URL193 # as its full_path and switch the proxy URL194 # for where the request will be sent.195 target_url = str(request.url)196 request.url = self.proxy_url.copy_with()197 request.url.full_path = target_url198 for name, value in self.proxy_headers.items():199 request.headers.setdefault(name, value)200201 return await super().send(request=request, timeout=timeout)202203 def __repr__(self) -> str:204 return (205 f"HTTPProxy(proxy_url={self.proxy_url!r} "206 f"proxy_headers={self.proxy_headers!r} "207 f"proxy_mode={self.proxy_mode!r})"208 )
modified:httpx/_dispatch/urllib3.py+60 added-27 removed
1import math2import socket3import ssl4import typing4from typing import Dict, Iterator, List, Optional, Tuple, Union56import httpcore7import urllib38from urllib3.exceptions import MaxRetryError, SSLError910from .._config import (
1 unmodified line
12 CertTypes,13 PoolLimits,14 Proxy,15 SSLConfig,15 Timeout,16 VerifyTypes,17)18from .._content_streams import IteratorStream19from .._models import Request, Response18from .._content_streams import ByteStream, IteratorStream19from .._utils import as_network_error21from .base import SyncDispatcher202124class URLLib3Dispatcher(SyncDispatcher):22class URLLib3Dispatcher(httpcore.SyncHTTPTransport):23 def __init__(24 self,25 *,26 proxy: Proxy = None,
32 unmodified lines
59 )6061 def init_pool_manager(62 self,65 proxy: typing.Optional[Proxy],63 proxy: Optional[Proxy],64 ssl_context: ssl.SSLContext,65 num_pools: int,66 maxsize: int,67 block: bool,70 ) -> typing.Union[urllib3.PoolManager, urllib3.ProxyManager]:68 ) -> Union[urllib3.PoolManager, urllib3.ProxyManager]:69 if proxy is None:70 return urllib3.PoolManager(71 ssl_context=ssl_context,72 num_pools=num_pools,
9 unmodified lines
82 maxsize=maxsize,83 block=block,84 )8588 def send(self, request: Request, timeout: Timeout = None) -> Response:89 timeout = Timeout() if timeout is None else timeout86 def request(87 self,88 method: bytes,89 url: Tuple[bytes, bytes, int, bytes],90 headers: List[Tuple[bytes, bytes]] = None,91 stream: httpcore.SyncByteStream = None,92 timeout: Dict[str, Optional[float]] = None,93 ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.SyncByteStream]:94 headers = [] if headers is None else headers95 stream = ByteStream(b"") if stream is None else stream96 timeout = {} if timeout is None else timeout9798 urllib3_timeout = urllib3.util.Timeout(91 connect=timeout.connect_timeout, read=timeout.read_timeout99 connect=timeout.get("connect"), read=timeout.get("read")100 )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 None101102 chunked = False103 content_length = 0104 for header_key, header_value in headers:105 header_key = header_key.lower()106 if header_key == b"transfer-encoding":107 chunked = header_value == b"chunked"108 if header_key == b"content-length":109 content_length = int(header_value.decode("ascii"))110 body = stream if chunked or content_length else None111112 scheme, host, port, path = url113 default_scheme = {80: b"http", 443: "https"}.get(port)114 if scheme == default_scheme:115 url_str = "%s://%s%s" % (116 scheme.decode("ascii"),117 host.decode("ascii"),118 path.decode("ascii"),119 )120 else:121 url_str = "%s://%s:%d%s" % (122 scheme.decode("ascii"),123 host.decode("ascii"),124 port,125 path.decode("ascii"),126 )127128 with as_network_error(MaxRetryError, SSLError, socket.error):129 conn = self.pool.urlopen(99 method=request.method,100 url=str(request.url),101 headers=dict(request.headers),130 method=method.decode(),131 url=url_str,132 headers=dict(133 [134 (key.decode("ascii"), value.decode("ascii"))135 for key, value in headers136 ]137 ),138 body=body,139 redirect=False,140 assert_same_host=False,141 retries=0,142 preload_content=False,143 chunked=chunked,144 timeout=urllib3_timeout,109 pool_timeout=timeout.pool_timeout,145 pool_timeout=timeout.get("pool"),146 )147112 def response_bytes() -> typing.Iterator[bytes]:148 def response_bytes() -> Iterator[bytes]:149 with as_network_error(socket.error):150 for chunk in conn.stream(4096, decode_content=False):151 yield chunk152117 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_conn153 status_code = conn.status154 headers = list(conn.headers.items())155 response_stream = IteratorStream(156 iterator=response_bytes(), close_func=conn.release_conn123 ),124 request=request,157 )158 return (b"HTTP/1.1", status_code, conn.reason, headers, response_stream)159160 def close(self) -> None:161 self.pool.clear()
modified:httpx/_dispatch/wsgi.py+42 added-24 removed
1import io2import itertools3import typing45from .._config import TimeoutTypes6from .._content_streams import IteratorStream7from .._models import Request, Response8from .base import SyncDispatcher5import httpcore67from .._content_streams import ByteStream, IteratorStream8910def _skip_leading_empty_chunks(body: typing.Iterable) -> typing.Iterable:11 body = iter(body)12 for chunk in body:13 if chunk:14 return itertools.chain([chunk], body)15 return []161719class WSGIDispatch(SyncDispatcher):18class WSGIDispatch(httpcore.SyncHTTPTransport):19 """21 A custom SyncDispatcher that handles sending requests directly to an WSGI app.20 A custom transport that handles sending requests directly to an WSGI app.21 The simplest way to use this functionality is to use the `app` argument.2223 ```24 client = httpx.Client(app=app)
34 unmodified lines
59 self.raise_app_exceptions = raise_app_exceptions60 self.script_name = script_name61 self.remote_addr = remote_addr6264 def send(self, request: Request, timeout: TimeoutTypes = None) -> Response:63 def request(64 self,65 method: bytes,66 url: typing.Tuple[bytes, bytes, int, bytes],67 headers: typing.List[typing.Tuple[bytes, bytes]] = None,68 stream: httpcore.SyncByteStream = None,69 timeout: typing.Dict[str, typing.Optional[float]] = None,70 ) -> typing.Tuple[71 bytes,72 int,73 bytes,74 typing.List[typing.Tuple[bytes, bytes]],75 httpcore.SyncByteStream,76 ]:77 headers = [] if headers is None else headers78 stream = ByteStream(b"") if stream is None else stream7980 scheme, host, port, full_path = url81 path, _, query = full_path.partition(b"?")82 environ = {83 "wsgi.version": (1, 0),67 "wsgi.url_scheme": request.url.scheme,68 "wsgi.input": io.BytesIO(request.read()),84 "wsgi.url_scheme": scheme.decode("ascii"),85 "wsgi.input": io.BytesIO(b"".join([chunk for chunk in stream])),86 "wsgi.errors": io.BytesIO(),87 "wsgi.multithread": True,88 "wsgi.multiprocess": False,89 "wsgi.run_once": False,73 "REQUEST_METHOD": request.method,90 "REQUEST_METHOD": method.decode(),91 "SCRIPT_NAME": self.script_name,75 "PATH_INFO": request.url.path,76 "QUERY_STRING": request.url.query,77 "SERVER_NAME": request.url.host,78 "SERVER_PORT": str(request.url.port),92 "PATH_INFO": path.decode("ascii"),93 "QUERY_STRING": query.decode("ascii"),94 "SERVER_NAME": host.decode("ascii"),95 "SERVER_PORT": str(port),96 "REMOTE_ADDR": self.remote_addr,97 }81 for key, value in request.headers.items():82 key = key.upper().replace("-", "_")98 for header_key, header_value in headers:99 key = header_key.decode("ascii").upper().replace("-", "_")100 if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):101 key = "HTTP_" + key85 environ[key] = value102 environ[key] = header_value.decode("ascii")103104 seen_status = None105 seen_response_headers = None106 seen_exc_info = None
15 unmodified lines
122 assert seen_response_headers is not None123 if seen_exc_info and self.raise_app_exceptions:124 raise seen_exc_info[1]125109 return Response(110 status_code=int(seen_status.split()[0]),111 http_version="HTTP/1.1",112 headers=seen_response_headers,113 stream=IteratorStream(chunk for chunk in result),114 request=request,115 )126 status_code = int(seen_status.split()[0])127 headers = [128 (key.encode("ascii"), value.encode("ascii"))129 for key, value in seen_response_headers130 ]131 stream = IteratorStream(chunk for chunk in result)132133 return (b"HTTP/1.1", status_code, b"", headers, stream)
modified:httpx/__init__.py-4 removed
4 unmodified lines
5from ._config import PoolLimits, Proxy, Timeout6from ._dispatch.asgi import ASGIDispatch7from ._dispatch.wsgi import WSGIDispatch8from ._exceptions import (9 ConnectionClosed,9 ConnectTimeout,10 CookieConflict,11 DecodingError,12 HTTPError,
8 unmodified lines
21 RequestNotRead,22 ResponseClosed,23 ResponseNotRead,24 StreamConsumed,26 TimeoutException,25 TooManyRedirects,26 WriteTimeout,27)28from ._models import URL, Cookies, Headers, QueryParams, Request, Response
24 unmodified lines
53 "Proxy",54 "Timeout",55 "ConnectTimeout",56 "CookieConflict",59 "ConnectionClosed",57 "DecodingError",58 "HTTPError",59 "InvalidURL",60 "NetworkError",
14 unmodified lines
75 "Cookies",76 "Headers",77 "QueryParams",78 "Request",82 "TimeoutException",79 "Response",80 "DigestAuth",81 "WSGIDispatch",82]
modified:httpx/__version__.py+1 added-1 removed
1__title__ = "httpx"2__description__ = "A next generation HTTP client, for Python 3."3__version__ = "0.12.1"3__version__ = "0.13.dev0"
modified:httpx/_client.py+106 added-51 removed
1 unmodified line
2import typing3from types import TracebackType45import hstspreload6import httpcore78from ._auth import Auth, AuthTypes, BasicAuth, FunctionAuth9from ._config import (10 DEFAULT_MAX_REDIRECTS,
3 unmodified lines
14 CertTypes,15 PoolLimits,16 ProxiesTypes,17 Proxy,18 SSLConfig,19 Timeout,20 TimeoutTypes,21 UnsetType,22 VerifyTypes,23)24from ._content_streams import ContentStream25from ._dispatch.asgi import ASGIDispatch24from ._dispatch.base import AsyncDispatcher, SyncDispatcher25from ._dispatch.connection_pool import ConnectionPool26from ._dispatch.proxy_http import HTTPProxy27from ._dispatch.urllib3 import URLLib3Dispatcher26from ._dispatch.wsgi import WSGIDispatch27from ._exceptions import HTTPError, InvalidURL, RequestBodyUnavailable, TooManyRedirects28from ._models import (29 URL,
63 unmodified lines
93 return {}94 elif isinstance(proxies, (str, URL, Proxy)):95 proxy = Proxy(url=proxies) if isinstance(proxies, (str, URL)) else proxies96 return {"all": proxy}99 elif isinstance(proxies, AsyncDispatcher): # pragma: nocover97 elif isinstance(proxies, httpcore.AsyncHTTPTransport): # pragma: nocover98 raise RuntimeError(99 "Passing a dispatcher instance to 'proxies=' is no longer "100 "supported. Use `httpx.Proxy() instead.`"101 )
2 unmodified lines
104 for key, value in proxies.items():105 if isinstance(value, (str, URL, Proxy)):106 proxy = Proxy(url=value) if isinstance(value, (str, URL)) else value107 new_proxies[str(key)] = proxy110 elif isinstance(value, AsyncDispatcher): # pragma: nocover108 elif isinstance(value, httpcore.AsyncHTTPTransport): # pragma: nocover109 raise RuntimeError(110 "Passing a dispatcher instance to 'proxies=' is "111 "no longer supported. Use `httpx.Proxy() instead.`"112 )
330 unmodified lines
443 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,444 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,445 max_redirects: int = DEFAULT_MAX_REDIRECTS,446 base_url: URLTypes = None,449 dispatch: SyncDispatcher = None,447 dispatch: httpcore.SyncHTTPTransport = None,448 app: typing.Callable = None,449 trust_env: bool = True,450 ):451 super().__init__(
16 unmodified lines
468 dispatch=dispatch,469 app=app,470 trust_env=trust_env,471 )474 self.proxies: typing.Dict[str, SyncDispatcher] = {472 self.proxies: typing.Dict[str, httpcore.SyncHTTPTransport] = {473 key: self.init_proxy_dispatch(474 proxy,475 verify=verify,476 cert=cert,
7 unmodified lines
484 self,485 verify: VerifyTypes = True,486 cert: CertTypes = None,487 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,490 dispatch: SyncDispatcher = None,488 dispatch: httpcore.SyncHTTPTransport = None,489 app: typing.Callable = None,490 trust_env: bool = True,493 ) -> SyncDispatcher:491 ) -> httpcore.SyncHTTPTransport:492 if dispatch is not None:493 return dispatch494495 if app is not None:496 return WSGIDispatch(app=app)497500 return URLLib3Dispatcher(501 verify=verify, cert=cert, pool_limits=pool_limits, trust_env=trust_env,498 ssl_context = SSLConfig(499 verify=verify, cert=cert, trust_env=trust_env500 ).ssl_context501 max_keepalive = pool_limits.soft_limit502 max_connections = pool_limits.hard_limit503504 return httpcore.SyncConnectionPool(505 ssl_context=ssl_context,506 max_keepalive=max_keepalive,507 max_connections=max_connections,508 )509510 def init_proxy_dispatch(511 self,
1 unmodified line
513 verify: VerifyTypes = True,514 cert: CertTypes = None,515 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,516 trust_env: bool = True,511 ) -> SyncDispatcher:512 return URLLib3Dispatcher(513 proxy=proxy,514 verify=verify,515 cert=cert,516 pool_limits=pool_limits,517 trust_env=trust_env,517 ) -> httpcore.SyncHTTPTransport:518 ssl_context = SSLConfig(519 verify=verify, cert=cert, trust_env=trust_env520 ).ssl_context521 max_keepalive = pool_limits.soft_limit522 max_connections = pool_limits.hard_limit523524 return httpcore.SyncHTTPProxy(525 proxy_origin=proxy.url.raw[:3],526 proxy_headers=proxy.headers.raw,527 proxy_mode=proxy.mode,528 ssl_context=ssl_context,529 max_keepalive=max_keepalive,530 max_connections=max_connections,531 )532520 def dispatcher_for_url(self, url: URL) -> SyncDispatcher:533 def dispatcher_for_url(self, url: URL) -> httpcore.SyncHTTPTransport:534 """522 Returns the SyncDispatcher instance that should be used for a given URL.535 Returns the transport instance that should be used for a given URL.536 This will either be the standard connection pool, or a proxy.537 """538 if self.proxies and not should_not_be_proxied(url):539 is_default_port = (url.scheme == "http" and url.port == 80) or (
139 unmodified lines
679 response.read()680 request = next_request681 history.append(response)682670 def send_single_request(self, request: Request, timeout: Timeout,) -> Response:683 def send_single_request(self, request: Request, timeout: Timeout) -> Response:684 """685 Sends a single request, without handling any redirections.686 """687688 dispatcher = self.dispatcher_for_url(request.url)689690 try:678 response = dispatcher.send(request, timeout=timeout)691 (692 http_version,693 status_code,694 reason_phrase,695 headers,696 stream,697 ) = dispatcher.request(698 request.method.encode(),699 request.url.raw,700 headers=request.headers.raw,701 stream=request.stream,702 timeout=timeout.as_dict(),703 )704 except HTTPError as exc:705 # Add the original request to any HTTPError unless706 # there'a already a request attached in the case of707 # a ProxyError.708 if exc._request is None:709 exc._request = request710 raise711 response = Response(712 status_code,713 http_version=http_version.decode("ascii"),714 headers=headers,715 stream=stream, # type: ignore716 request=request,717 )718719 self.cookies.extract_cookies(response)720721 status = f"{response.status_code} {response.reason_phrase}"
237 unmodified lines
959 * **app** - *(optional)* An ASGI application to send requests to,960 rather than sending actual network requests.961 * **trust_env** - *(optional)* Enables or disables usage of environment962 variables for configuration.931 * **uds** - *(optional)* A path to a Unix domain socket to connect through.963 """964965 def __init__(966 self,
9 unmodified lines
976 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,977 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,978 max_redirects: int = DEFAULT_MAX_REDIRECTS,979 base_url: URLTypes = None,949 dispatch: AsyncDispatcher = None,980 dispatch: httpcore.AsyncHTTPTransport = None,981 app: typing.Callable = None,982 trust_env: bool = True,952 uds: str = None,983 ):984 super().__init__(985 auth=auth,986 params=params,
14 unmodified lines
1001 pool_limits=pool_limits,1002 dispatch=dispatch,1003 app=app,1004 trust_env=trust_env,975 uds=uds,1005 )977 self.proxies: typing.Dict[str, AsyncDispatcher] = {1006 self.proxies: typing.Dict[str, httpcore.AsyncHTTPTransport] = {1007 key: self.init_proxy_dispatch(1008 proxy,1009 verify=verify,1010 cert=cert,
9 unmodified lines
1020 verify: VerifyTypes = True,1021 cert: CertTypes = None,1022 http2: bool = False,1023 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,995 dispatch: AsyncDispatcher = None,1024 dispatch: httpcore.AsyncHTTPTransport = None,1025 app: typing.Callable = None,1026 trust_env: bool = True,998 uds: str = None,999 ) -> AsyncDispatcher:1027 ) -> httpcore.AsyncHTTPTransport:1028 if dispatch is not None:1029 return dispatch10301031 if app is not None:1032 return ASGIDispatch(app=app)10331006 return ConnectionPool(1007 verify=verify,1008 cert=cert,1034 ssl_context = SSLConfig(1035 verify=verify, cert=cert, trust_env=trust_env1036 ).ssl_context1037 max_keepalive = pool_limits.soft_limit1038 max_connections = pool_limits.hard_limit10391040 return httpcore.AsyncConnectionPool(1041 ssl_context=ssl_context,1042 max_keepalive=max_keepalive,1043 max_connections=max_connections,1044 http2=http2,1010 pool_limits=pool_limits,1011 trust_env=trust_env,1012 uds=uds,1045 )10461047 def init_proxy_dispatch(1048 self,
2 unmodified lines
1051 cert: CertTypes = None,1052 http2: bool = False,1053 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,1054 trust_env: bool = True,1023 ) -> AsyncDispatcher:1024 return HTTPProxy(1025 proxy_url=proxy.url,1026 proxy_headers=proxy.headers,1055 ) -> httpcore.AsyncHTTPTransport:1056 ssl_context = SSLConfig(1057 verify=verify, cert=cert, trust_env=trust_env1058 ).ssl_context1059 max_keepalive = pool_limits.soft_limit1060 max_connections = pool_limits.hard_limit10611062 return httpcore.AsyncHTTPProxy(1063 proxy_origin=proxy.url.raw[:3],1064 proxy_headers=proxy.headers.raw,1065 proxy_mode=proxy.mode,1028 verify=verify,1029 cert=cert,1030 http2=http2,1031 pool_limits=pool_limits,1032 trust_env=trust_env,1066 ssl_context=ssl_context,1067 max_keepalive=max_keepalive,1068 max_connections=max_connections,1069 )10701035 def dispatcher_for_url(self, url: URL) -> AsyncDispatcher:1071 def dispatcher_for_url(self, url: URL) -> httpcore.AsyncHTTPTransport:1072 """1037 Returns the AsyncDispatcher instance that should be used for a given URL.1073 Returns the transport instance that should be used for a given URL.1074 This will either be the standard connection pool, or a proxy.1075 """1076 if self.proxies and not should_not_be_proxied(url):1077 is_default_port = (url.scheme == "http" and url.port == 80) or (
150 unmodified lines
12281229 dispatcher = self.dispatcher_for_url(request.url)12301231 try:1196 response = await dispatcher.send(request, timeout=timeout)1232 (1233 http_version,1234 status_code,1235 reason_phrase,1236 headers,1237 stream,1238 ) = await dispatcher.request(1239 request.method.encode(),1240 request.url.raw,1241 headers=request.headers.raw,1242 stream=request.stream,1243 timeout=timeout.as_dict(),1244 )1245 except HTTPError as exc:1246 # Add the original request to any HTTPError unless1247 # there'a already a request attached in the case of1248 # a ProxyError.1249 if exc._request is None:1250 exc._request = request1251 raise1252 response = Response(1253 status_code,1254 http_version=http_version.decode("ascii"),1255 headers=headers,1256 stream=stream, # type: ignore1257 request=request,1258 )12591260 self.cookies.extract_cookies(response)12611262 status = f"{response.status_code} {response.reason_phrase}"
174 unmodified lines
1437 timeout=timeout,1438 )14391440 async def aclose(self) -> None:1386 await self.dispatch.close()1441 await self.dispatch.aclose()1442 for proxy in self.proxies.values():1388 await proxy.close()1443 await proxy.aclose()14441445 async def __aenter__(self) -> "AsyncClient":1446 return self1447
70 unmodified lines
modified:httpx/_config.py+8 added
251 unmodified lines
252 self.pool_timeout = (253 timeout if isinstance(pool_timeout, UnsetType) else pool_timeout254 )255256 def as_dict(self) -> typing.Dict[str, typing.Optional[float]]:257 return {258 "connect": self.connect_timeout,259 "read": self.read_timeout,260 "write": self.write_timeout,261 "pool": self.pool_timeout,262 }263264 def __eq__(self, other: typing.Any) -> bool:265 return (266 isinstance(other, self.__class__)267 and self.connect_timeout == other.connect_timeout
99 unmodified lines
modified:httpx/_content_streams.py+3 added-1 removed
5 unmodified lines
6from json import dumps as json_dumps7from pathlib import Path8from urllib.parse import urlencode910import httpcore1112from ._exceptions import StreamConsumed13from ._types import StrOrBytes14from ._utils import format_form_param15
20 unmodified lines
36 ],37]383938class ContentStream:40class ContentStream(httpcore.AsyncByteStream, httpcore.SyncByteStream):41 def get_headers(self) -> typing.Dict[str, str]:42 """43 Return a dictionary of headers that are implied by the encoding.44 """
309 unmodified lines
modified:httpx/_exceptions.py+15 added-50 removed
1import typing23import httpcore45if typing.TYPE_CHECKING:6 from ._models import Request, Response # pragma: nocover78
18 unmodified lines
272829# Timeout exceptions...3031ConnectTimeout = httpcore.ConnectTimeout32ReadTimeout = httpcore.ReadTimeout33WriteTimeout = httpcore.WriteTimeout34PoolTimeout = httpcore.PoolTimeout3530class TimeoutException(HTTPError):31 """32 A base class for all timeouts.33 """3637# Core networking exceptions...3836class ConnectTimeout(TimeoutException):37 """38 Timeout while establishing a connection.39 """39NetworkError = httpcore.NetworkError40ReadError = httpcore.ReadError41WriteError = httpcore.WriteError42ConnectError = httpcore.ConnectError43CloseError = httpcore.CloseError444542class ReadTimeout(TimeoutException):43 """44 Timeout while reading response data.45 """46# Other transport exceptions...4748ProxyError = httpcore.ProxyError49ProtocolError = httpcore.ProtocolError5048class WriteTimeout(TimeoutException):49 """50 Timeout while writing request data.51 """515354class PoolTimeout(TimeoutException):55 """56 Timeout while waiting to acquire a connection from the pool.57 """585960class ProxyError(HTTPError):61 """62 Error from within a proxy63 """646552# HTTP exceptions...535469class ProtocolError(HTTPError):70 """71 Malformed HTTP.72 """737455class DecodingError(HTTPError):56 """57 Decoding of the response failed.58 """596081# Network exceptions...828384class NetworkError(HTTPError):85 """86 A failure occurred while trying to access the network.87 """888990class ConnectionClosed(NetworkError):91 """92 Expected more data from peer, but connection was closed.93 """949561# Redirect exceptions...626364class RedirectError(HTTPError):
76 unmodified lines
modified:httpx/_models.py+9 added
173 unmodified lines
174 def fragment(self) -> str:175 return self._uri_reference.fragment or ""176177 @property178 def raw(self) -> typing.Tuple[bytes, bytes, int, bytes]:179 return (180 self.scheme.encode("ascii"),181 self.host.encode("ascii"),182 self.port,183 self.full_path.encode("ascii"),184 )185186 @property187 def is_ssl(self) -> bool:188 return self.scheme == "https"189190 @property
1027 unmodified lines
modified:tests/client/test_async_client.py-12 removed
146 unmodified lines
147 )148149 assert response.status_code == 200150 assert response.content == data151152153@pytest.mark.usefixtures("async_environment")154async def test_uds(uds_server):155 url = uds_server.url156 uds = uds_server.config.uds157 assert uds is not None158 async with httpx.AsyncClient(uds=uds) as client:159 response = await client.get(url)160 assert response.status_code == 200161 assert response.text == "Hello, world!"162 assert response.encoding == "iso-8859-1"
modified:tests/client/test_auth.py+58 added-37 removed
1import hashlib2import json2import os3import typing45import httpcore6import pytest78from httpx import (9 URL,10 AsyncClient,11 Auth,12 DigestAuth,13 Headers,14 ProtocolError,15 Request,16 RequestBodyUnavailable,17 Response,18)18from httpx._config import CertTypes, TimeoutTypes, VerifyTypes19from httpx._dispatch.base import AsyncDispatcher19from httpx._content_streams import ContentStream, JSONStream202122def get_header_value(headers, key, default=None):23 lookup = key.encode("ascii").lower()24 for header_key, header_value in headers:25 if header_key.lower() == lookup:26 return header_value.decode("ascii")27 return default282922class MockDispatch(AsyncDispatcher):23 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:30class MockDispatch(httpcore.AsyncHTTPTransport):31 def __init__(self, auth_header: bytes = b"", status_code: int = 200) -> None:32 self.auth_header = auth_header33 self.status_code = status_code3427 async def send(35 async def request(36 self,29 request: Request,30 verify: VerifyTypes = None,31 cert: CertTypes = None,32 timeout: TimeoutTypes = None,33 ) -> Response:34 headers = [("www-authenticate", self.auth_header)] if self.auth_header else []35 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()36 return Response(37 self.status_code, headers=headers, content=body, request=request37 method: bytes,38 url: typing.Tuple[bytes, bytes, int, bytes],39 headers: typing.List[typing.Tuple[bytes, bytes]],40 stream: ContentStream,41 timeout: typing.Dict[str, typing.Optional[float]] = None,42 ) -> typing.Tuple[43 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream44 ]:45 authorization = get_header_value(headers, "Authorization")46 response_headers = (47 [(b"www-authenticate", self.auth_header)] if self.auth_header else []48 )49 response_stream = JSONStream({"auth": authorization})50 return b"HTTP/1.1", self.status_code, b"", response_headers, response_stream515241class MockDigestAuthDispatch(AsyncDispatcher):53class MockDigestAuthDispatch(httpcore.AsyncHTTPTransport):54 def __init__(55 self,56 algorithm: str = "SHA-256",57 send_response_after_attempt: int = 1,
5 unmodified lines
63 self.qop = qop64 self._regenerate_nonce = regenerate_nonce65 self._response_count = 06655 async def send(67 async def request(68 self,57 request: Request,58 verify: VerifyTypes = None,59 cert: CertTypes = None,60 timeout: TimeoutTypes = None,61 ) -> Response:69 method: bytes,70 url: typing.Tuple[bytes, bytes, int, bytes],71 headers: typing.List[typing.Tuple[bytes, bytes]],72 stream: ContentStream,73 timeout: typing.Dict[str, typing.Optional[float]] = None,74 ) -> typing.Tuple[75 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream76 ]:77 if self._response_count < self.send_response_after_attempt:63 return self.challenge_send(request)78 return self.challenge_send(method, url, headers, stream)7965 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()66 return Response(200, content=body, request=request)80 authorization = get_header_value(headers, "Authorization")81 body = JSONStream({"auth": authorization})82 return b"HTTP/1.1", 200, b"", [], body8368 def challenge_send(self, request: Request) -> Response:84 def challenge_send(85 self, method: bytes, url: URL, headers: Headers, stream: ContentStream,86 ) -> typing.Tuple[int, bytes, Headers, ContentStream]:87 self._response_count += 188 nonce = (89 hashlib.sha256(os.urandom(8)).hexdigest()90 if self._regenerate_nonce
14 unmodified lines
105 if value106 )107108 headers = [91 ("www-authenticate", 'Digest realm="httpx@example.org", ' + challenge_str)109 (110 b"www-authenticate",111 b'Digest realm="httpx@example.org", ' + challenge_str.encode("ascii"),112 )113 ]93 return Response(401, headers=headers, content=b"", request=request)114 return b"HTTP/1.1", 401, b"", headers, ContentStream()115116117@pytest.mark.asyncio118async def test_basic_auth() -> None:
135 unmodified lines
254@pytest.mark.asyncio255async def test_digest_auth_200_response_including_digest_auth_header() -> None:256 url = "https://example.org/"257 auth = DigestAuth(username="tomchristie", password="password123")237 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'258 auth_header = b'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'259260 client = AsyncClient(261 dispatch=MockDispatch(auth_header=auth_header, status_code=200)262 )
8 unmodified lines
271async def test_digest_auth_401_response_without_digest_auth_header() -> None:272 url = "https://example.org/"273 auth = DigestAuth(username="tomchristie", password="password123")274254 client = AsyncClient(dispatch=MockDispatch(auth_header="", status_code=401))275 client = AsyncClient(dispatch=MockDispatch(auth_header=b"", status_code=401))276 response = await client.get(url, auth=auth)277278 assert response.status_code == 401279 assert response.json() == {"auth": None}
122 unmodified lines
402403@pytest.mark.parametrize(404 "auth_header",405 [385 'Digest realm="httpx@example.org", qop="auth"', # missing fields386 'realm="httpx@example.org", qop="auth"', # not starting with Digest387 'DigestZ realm="httpx@example.org", qop="auth"'388 'qop="auth,auth-int",nonce="abc",opaque="xyz"',389 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list406 b'Digest realm="httpx@example.org", qop="auth"', # missing fields407 b'realm="httpx@example.org", qop="auth"', # not starting with Digest408 b'DigestZ realm="httpx@example.org", qop="auth"'409 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',410 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list411 ],412)413@pytest.mark.asyncio414async def test_digest_auth_raises_protocol_error_on_malformed_header(394 auth_header: str,415 auth_header: bytes,416) -> None:417 url = "https://example.org/"418 auth = DigestAuth(username="tomchristie", password="password123")419 client = AsyncClient(
39 unmodified lines
459 yield request460461 url = "https://example.org/"462 auth = RepeatAuth(repeat=2)442 client = AsyncClient(dispatch=MockDispatch(auth_header="abc"))463 client = AsyncClient(dispatch=MockDispatch(auth_header=b"abc"))464465 response = await client.get(url, auth=auth)466 assert response.status_code == 200467 assert response.json() == {"auth": "Repeat abc.abc"}
60 unmodified lines
modified:tests/client/test_cookies.py+32 added-18 removed
1import json1import typing2from http.cookiejar import Cookie, CookieJar34import httpcore5import pytest66from httpx import AsyncClient, Cookies, Request, Response7from httpx._config import CertTypes, TimeoutTypes, VerifyTypes8from httpx._dispatch.base import AsyncDispatcher7from httpx import AsyncClient, Cookies8from httpx._content_streams import ByteStream, ContentStream, JSONStream91011class MockDispatch(AsyncDispatcher):12 async def send(11def get_header_value(headers, key, default=None):12 lookup = key.encode("ascii").lower()13 for header_key, header_value in headers:14 if header_key.lower() == lookup:15 return header_value.decode("ascii")16 return default171819class MockDispatch(httpcore.AsyncHTTPTransport):20 async def request(21 self,14 request: Request,15 verify: VerifyTypes = None,16 cert: CertTypes = None,17 timeout: TimeoutTypes = None,18 ) -> Response:19 if request.url.path.startswith("/echo_cookies"):20 body = json.dumps({"cookies": request.headers.get("Cookie")}).encode()21 return Response(200, content=body, request=request)22 elif request.url.path.startswith("/set_cookie"):23 headers = {"set-cookie": "example-name=example-value"}24 return Response(200, headers=headers, request=request)22 method: bytes,23 url: typing.Tuple[bytes, bytes, int, bytes],24 headers: typing.List[typing.Tuple[bytes, bytes]],25 stream: ContentStream,26 timeout: typing.Dict[str, typing.Optional[float]] = None,27 ) -> typing.Tuple[28 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream29 ]:30 host, scheme, port, path = url31 if path.startswith(b"/echo_cookies"):32 cookie = get_header_value(headers, "cookie")33 body = JSONStream({"cookies": cookie})34 return b"HTTP/1.1", 200, b"OK", [], body35 elif path.startswith(b"/set_cookie"):36 headers = [(b"set-cookie", b"example-name=example-value")]37 body = ByteStream(b"")38 return b"HTTP/1.1", 200, b"OK", headers, body39 else:26 raise NotImplementedError # pragma: no cover40 raise NotImplementedError() # pragma: no cover414243@pytest.mark.asyncio44async def test_set_cookie() -> None:
134 unmodified lines
modified:tests/client/test_headers.py+19 added-15 removed
1#!/usr/bin/env python323import json3import typing45import httpcore6import pytest77from httpx import AsyncClient, Headers, Request, Response, __version__8from httpx._config import CertTypes, TimeoutTypes, VerifyTypes9from httpx._dispatch.base import AsyncDispatcher8from httpx import AsyncClient, Headers, __version__9from httpx._content_streams import ContentStream, JSONStream101112class MockDispatch(AsyncDispatcher):13 async def send(12class MockDispatch(httpcore.AsyncHTTPTransport):13 async def request(14 self,15 request: Request,16 verify: VerifyTypes = None,17 cert: CertTypes = None,18 timeout: TimeoutTypes = None,19 ) -> Response:20 if request.url.path.startswith("/echo_headers"):21 request_headers = dict(request.headers.items())22 body = json.dumps({"headers": request_headers}).encode()23 return Response(200, content=body, request=request)15 method: bytes,16 url: typing.Tuple[bytes, bytes, int, bytes],17 headers: typing.List[typing.Tuple[bytes, bytes]],18 stream: ContentStream,19 timeout: typing.Dict[str, typing.Optional[float]] = None,20 ) -> typing.Tuple[21 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream22 ]:23 headers_dict = dict(24 [(key.decode("ascii"), value.decode("ascii")) for key, value in headers]25 )26 body = JSONStream({"headers": headers_dict})27 return b"HTTP/1.1", 200, b"OK", [], body282930@pytest.mark.asyncio31async def test_client_header():
151 unmodified lines
modified:tests/client/test_proxies.py+3 added-3 removed
22 unmodified lines
23 client = httpx.AsyncClient(proxies=proxies)2425 for proxy_key, url in expected_proxies:26 assert proxy_key in client.proxies27 assert client.proxies[proxy_key].proxy_url == url27 assert client.proxies[proxy_key].proxy_origin == httpx.URL(url).raw[:3]2829 assert len(expected_proxies) == len(client.proxies)3031
48 unmodified lines
8081 if expected is None:82 assert dispatcher is client.dispatch83 else:84 assert dispatcher.proxy_url == expected84 assert dispatcher.proxy_origin == httpx.URL(expected).raw[:3]858687def test_unsupported_proxy_scheme():88 with pytest.raises(ValueError):
25 unmodified lines
114115 if expected is None:116 assert dispatcher == client.dispatch117 else:118 assert dispatcher.proxy_url == expected118 assert dispatcher.proxy_origin == httpx.URL(expected).raw[:3]
modified:tests/client/test_queryparams.py+17 added-14 removed
1import json1import typing23import httpcore4import pytest55from httpx import URL, AsyncClient, QueryParams, Request, Response6from httpx._config import CertTypes, TimeoutTypes, VerifyTypes7from httpx._dispatch.base import AsyncDispatcher6from httpx import URL, AsyncClient, Headers, QueryParams7from httpx._content_streams import ContentStream, JSONStream8910class MockDispatch(AsyncDispatcher):11 async def send(10class MockDispatch(httpcore.AsyncHTTPTransport):11 async def request(12 self,13 request: Request,14 verify: VerifyTypes = None,15 cert: CertTypes = None,16 timeout: TimeoutTypes = None,17 ) -> Response:18 if request.url.path.startswith("/echo_queryparams"):19 body = json.dumps({"ok": "ok"}).encode()20 return Response(200, content=body, request=request)13 method: bytes,14 url: typing.Tuple[bytes, bytes, int, bytes],15 headers: typing.List[typing.Tuple[bytes, bytes]],16 stream: ContentStream,17 timeout: typing.Dict[str, typing.Optional[float]] = None,18 ) -> typing.Tuple[19 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream20 ]:21 headers = Headers()22 body = JSONStream({"ok": "ok"})23 return b"HTTP/1.1", 200, b"OK", headers, body242526def test_client_queryparams():27 client = AsyncClient(params={"a": "b"})
27 unmodified lines
modified:tests/client/test_redirects.py+135 added-97 removed
1import json2import typing3from urllib.parse import parse_qs45import httpcore6import pytest78from httpx import (9 URL,10 AsyncClient,11 NotRedirectResponse,10 Request,12 RequestBodyUnavailable,12 Response,13 TooManyRedirects,14 codes,15)16from httpx._config import CertTypes, TimeoutTypes, VerifyTypes17from httpx._content_streams import AsyncIteratorStream18from httpx._dispatch.base import AsyncDispatcher16from httpx._content_streams import AsyncIteratorStream, ByteStream, ContentStream171821class MockDispatch(AsyncDispatcher):22 async def send(19def get_header_value(headers, key, default=None):20 lookup = key.encode("ascii").lower()21 for header_key, header_value in headers:22 if header_key.lower() == lookup:23 return header_value.decode("ascii")24 return default252627class MockDispatch(httpcore.AsyncHTTPTransport):28 async def request(29 self,24 request: Request,25 verify: VerifyTypes = None,26 cert: CertTypes = None,27 timeout: TimeoutTypes = None,28 ) -> Response:29 if request.url.path == "/no_redirect":30 return Response(codes.OK, request=request)30 method: bytes,31 url: typing.Tuple[bytes, bytes, int, bytes],32 headers: typing.List[typing.Tuple[bytes, bytes]],33 stream: ContentStream,34 timeout: typing.Dict[str, typing.Optional[float]] = None,35 ) -> typing.Tuple[36 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream37 ]:38 scheme, host, port, path = url39 path, _, query = path.partition(b"?")40 if path == b"/no_redirect":41 return b"HTTP/1.1", codes.OK, b"OK", [], ByteStream(b"")4232 elif request.url.path == "/redirect_301":43 elif path == b"/redirect_301":4445 async def body():46 yield b"<a href='https://example.org/'>here</a>"4748 status_code = codes.MOVED_PERMANENTLY38 headers = {"location": "https://example.org/"}49 headers = [(b"location", b"https://example.org/")]50 stream = AsyncIteratorStream(aiterator=body())40 return Response(41 status_code, stream=stream, headers=headers, request=request42 )51 return b"HTTP/1.1", status_code, b"Moved Permanently", headers, stream5244 elif request.url.path == "/redirect_302":53 elif path == b"/redirect_302":54 status_code = codes.FOUND46 headers = {"location": "https://example.org/"}47 return Response(status_code, headers=headers, request=request)55 headers = [(b"location", b"https://example.org/")]56 return b"HTTP/1.1", status_code, b"Found", headers, ByteStream(b"")5749 elif request.url.path == "/redirect_303":58 elif path == b"/redirect_303":59 status_code = codes.SEE_OTHER51 headers = {"location": "https://example.org/"}52 return Response(status_code, headers=headers, request=request)60 headers = [(b"location", b"https://example.org/")]61 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")6254 elif request.url.path == "/relative_redirect":55 headers = {"location": "/"}56 return Response(codes.SEE_OTHER, headers=headers, request=request)63 elif path == b"/relative_redirect":64 status_code = codes.SEE_OTHER65 headers = [(b"location", b"/")]66 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")6758 elif request.url.path == "/malformed_redirect":59 headers = {"location": "https://:443/"}60 return Response(codes.SEE_OTHER, headers=headers, request=request)68 elif path == b"/malformed_redirect":69 status_code = codes.SEE_OTHER70 headers = [(b"location", b"https://:443/")]71 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")7262 elif request.url.path == "/no_scheme_redirect":63 headers = {"location": "//example.org/"}64 return Response(codes.SEE_OTHER, headers=headers, request=request)73 elif path == b"/no_scheme_redirect":74 status_code = codes.SEE_OTHER75 headers = [(b"location", b"//example.org/")]76 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")7766 elif request.url.path == "/multiple_redirects":67 params = parse_qs(request.url.query)78 elif path == b"/multiple_redirects":79 params = parse_qs(query.decode("ascii"))80 count = int(params.get("count", "0")[0])81 redirect_count = count - 182 code = codes.SEE_OTHER if count else codes.OK83 phrase = b"See Other" if count else b"OK"71 location = "/multiple_redirects"84 location = b"/multiple_redirects"85 if redirect_count:73 location += "?count=" + str(redirect_count)74 headers = {"location": location} if count else {}75 return Response(code, headers=headers, request=request)86 location += b"?count=" + str(redirect_count).encode("ascii")87 headers = [(b"location", location)] if count else []88 return b"HTTP/1.1", code, phrase, headers, ByteStream(b"")8977 if request.url.path == "/redirect_loop":78 headers = {"location": "/redirect_loop"}79 return Response(codes.SEE_OTHER, headers=headers, request=request)90 if path == b"/redirect_loop":91 code = codes.SEE_OTHER92 headers = [(b"location", b"/redirect_loop")]93 return b"HTTP/1.1", code, b"See Other", headers, ByteStream(b"")9481 elif request.url.path == "/cross_domain":82 headers = {"location": "https://example.org/cross_domain_target"}83 return Response(codes.SEE_OTHER, headers=headers, request=request)95 elif path == b"/cross_domain":96 code = codes.SEE_OTHER97 headers = [(b"location", b"https://example.org/cross_domain_target")]98 return b"HTTP/1.1", code, b"See Other", headers, ByteStream(b"")9985 elif request.url.path == "/cross_domain_target":86 headers = dict(request.headers.items())87 content = json.dumps({"headers": headers}).encode()88 return Response(codes.OK, content=content, request=request)100 elif path == b"/cross_domain_target":101 headers_dict = dict(102 [(key.decode("ascii"), value.decode("ascii")) for key, value in headers]103 )104 content = ByteStream(json.dumps({"headers": headers_dict}).encode())105 return b"HTTP/1.1", 200, b"OK", [], content10690 elif request.url.path == "/redirect_body":91 body = b"".join([part async for part in request.stream])92 headers = {"location": "/redirect_body_target"}93 return Response(codes.PERMANENT_REDIRECT, headers=headers, request=request)107 elif path == b"/redirect_body":108 _ = b"".join([part async for part in stream])109 code = codes.PERMANENT_REDIRECT110 headers = [(b"location", b"/redirect_body_target")]111 return b"HTTP/1.1", code, b"Permanent Redirect", headers, ByteStream(b"")11295 elif request.url.path == "/redirect_no_body":96 content = b"".join([part async for part in request.stream])97 headers = {"location": "/redirect_body_target"}98 return Response(codes.SEE_OTHER, headers=headers, request=request)113 elif path == b"/redirect_no_body":114 _ = b"".join([part async for part in stream])115 code = codes.SEE_OTHER116 headers = [(b"location", b"/redirect_body_target")]117 return b"HTTP/1.1", code, b"See Other", headers, ByteStream(b"")118100 elif request.url.path == "/redirect_body_target":101 content = b"".join([part async for part in request.stream])102 headers = dict(request.headers.items())103 body = json.dumps({"body": content.decode(), "headers": headers}).encode()104 return Response(codes.OK, content=body, request=request)119 elif path == b"/redirect_body_target":120 content = b"".join([part async for part in stream])121 headers_dict = dict(122 [(key.decode("ascii"), value.decode("ascii")) for key, value in headers]123 )124 body = ByteStream(125 json.dumps({"body": content.decode(), "headers": headers_dict}).encode()126 )127 return b"HTTP/1.1", 200, b"OK", [], body128106 elif request.url.path == "/cross_subdomain":107 if request.headers["host"] != "www.example.org":108 headers = {"location": "https://www.example.org/cross_subdomain"}109 return Response(110 codes.PERMANENT_REDIRECT, headers=headers, request=request129 elif path == b"/cross_subdomain":130 host = get_header_value(headers, "host")131 if host != "www.example.org":132 headers = [(b"location", b"https://www.example.org/cross_subdomain")]133 return (134 b"HTTP/1.1",135 codes.PERMANENT_REDIRECT,136 b"Permanent Redirect",137 headers,138 ByteStream(b""),139 )140 else:113 return Response(codes.OK, content=b"Hello, world!", request=request)141 return b"HTTP/1.1", 200, b"OK", [], ByteStream(b"Hello, world!")142115 return Response(codes.OK, content=b"Hello, world!", request=request)143 return b"HTTP/1.1", 200, b"OK", [], ByteStream(b"Hello, world!")144145146@pytest.mark.usefixtures("async_environment")147async def test_no_redirect():
205 unmodified lines
353 response = await client.get(url)354 assert response.url == URL("https://www.example.org/cross_subdomain")355356329class MockCookieDispatch(AsyncDispatcher):330 async def send(357class MockCookieDispatch(httpcore.AsyncHTTPTransport):358 async def request(359 self,332 request: Request,333 verify: VerifyTypes = None,334 cert: CertTypes = None,335 timeout: TimeoutTypes = None,336 ) -> Response:337 if request.url.path == "/":338 if "cookie" in request.headers:360 method: bytes,361 url: typing.Tuple[bytes, bytes, int, bytes],362 headers: typing.List[typing.Tuple[bytes, bytes]],363 stream: ContentStream,364 timeout: typing.Dict[str, typing.Optional[float]] = None,365 ) -> typing.Tuple[366 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream367 ]:368 scheme, host, port, path = url369 if path == b"/":370 cookie = get_header_value(headers, "Cookie")371 if cookie is not None:372 content = b"Logged in"373 else:374 content = b"Not logged in"342 return Response(codes.OK, content=content, request=request)375 return b"HTTP/1.1", 200, b"OK", [], ByteStream(content)376344 elif request.url.path == "/login":377 elif path == b"/login":378 status_code = codes.SEE_OTHER346 headers = {347 "location": "/",348 "set-cookie": (349 "session=eyJ1c2VybmFtZSI6ICJ0b21; path=/; Max-Age=1209600; "350 "httponly; samesite=lax"379 headers = [380 (b"location", b"/"),381 (382 b"set-cookie",383 (384 b"session=eyJ1c2VybmFtZSI6ICJ0b21; path=/; Max-Age=1209600; "385 b"httponly; samesite=lax"386 ),387 ),352 }388 ]389 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")390354 return Response(status_code, headers=headers, request=request)355356 elif request.url.path == "/logout":391 elif path == b"/logout":392 status_code = codes.SEE_OTHER358 headers = {359 "location": "/",360 "set-cookie": (361 "session=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; "362 "httponly; samesite=lax"393 headers = [394 (b"location", b"/"),395 (396 b"set-cookie",397 (398 b"session=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; "399 b"httponly; samesite=lax"400 ),401 ),364 }365 return Response(status_code, headers=headers, request=request)402 ]403 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")404405406@pytest.mark.usefixtures("async_environment")407async def test_redirect_cookie_behavior():
26 unmodified lines
deleted:tests/dispatch/__init__.py
deleted:tests/dispatch/test_connection_pools.py-246 removed
1import pytest23import httpx4from httpx._dispatch.connection_pool import ConnectionPool567@pytest.mark.usefixtures("async_environment")8async def test_keepalive_connections(server):9 """10 Connections should default to staying in a keep-alive state.11 """12 async with ConnectionPool() as http:13 response = await http.request("GET", server.url)14 await response.aread()15 assert len(http.active_connections) == 016 assert len(http.keepalive_connections) == 11718 response = await http.request("GET", server.url)19 await response.aread()20 assert len(http.active_connections) == 021 assert len(http.keepalive_connections) == 1222324@pytest.mark.usefixtures("async_environment")25async def test_keepalive_timeout(server):26 """27 Keep-alive connections should timeout.28 """29 async with ConnectionPool() as http:30 response = await http.request("GET", server.url)31 await response.aread()32 assert len(http.active_connections) == 033 assert len(http.keepalive_connections) == 13435 http.next_keepalive_check = 0.036 await http.check_keepalive_expiry()3738 assert len(http.active_connections) == 039 assert len(http.keepalive_connections) == 14041 async with ConnectionPool() as http:42 http.KEEP_ALIVE_EXPIRY = 0.04344 response = await http.request("GET", server.url)45 await response.aread()46 assert len(http.active_connections) == 047 assert len(http.keepalive_connections) == 14849 http.next_keepalive_check = 0.050 await http.check_keepalive_expiry()5152 assert len(http.active_connections) == 053 assert len(http.keepalive_connections) == 0545556@pytest.mark.usefixtures("async_environment")57async def test_differing_connection_keys(server):58 """59 Connections to differing connection keys should result in multiple connections.60 """61 async with ConnectionPool() as http:62 response = await http.request("GET", server.url)63 await response.aread()64 assert len(http.active_connections) == 065 assert len(http.keepalive_connections) == 16667 response = await http.request("GET", "http://localhost:8000/")68 await response.aread()69 assert len(http.active_connections) == 070 assert len(http.keepalive_connections) == 2717273@pytest.mark.usefixtures("async_environment")74async def test_soft_limit(server):75 """76 The soft_limit config should limit the maximum number of keep-alive connections.77 """78 pool_limits = httpx.PoolLimits(soft_limit=1)7980 async with ConnectionPool(pool_limits=pool_limits) as http:81 response = await http.request("GET", server.url)82 await response.aread()83 assert len(http.active_connections) == 084 assert len(http.keepalive_connections) == 18586 response = await http.request("GET", "http://localhost:8000/")87 await response.aread()88 assert len(http.active_connections) == 089 assert len(http.keepalive_connections) == 1909192@pytest.mark.usefixtures("async_environment")93async def test_streaming_response_holds_connection(server):94 """95 A streaming request should hold the connection open until the response is read.96 """97 async with ConnectionPool() as http:98 response = await http.request("GET", server.url)99 assert len(http.active_connections) == 1100 assert len(http.keepalive_connections) == 0101102 await response.aread()103104 assert len(http.active_connections) == 0105 assert len(http.keepalive_connections) == 1106107108@pytest.mark.usefixtures("async_environment")109async def test_multiple_concurrent_connections(server):110 """111 Multiple concurrent requests should open multiple concurrent connections.112 """113 async with ConnectionPool() as http:114 response_a = await http.request("GET", server.url)115 assert len(http.active_connections) == 1116 assert len(http.keepalive_connections) == 0117118 response_b = await http.request("GET", server.url)119 assert len(http.active_connections) == 2120 assert len(http.keepalive_connections) == 0121122 await response_b.aread()123 assert len(http.active_connections) == 1124 assert len(http.keepalive_connections) == 1125126 await response_a.aread()127 assert len(http.active_connections) == 0128 assert len(http.keepalive_connections) == 2129130131@pytest.mark.usefixtures("async_environment")132async def test_close_connections(server):133 """134 Using a `Connection: close` header should close the connection.135 """136 headers = [(b"connection", b"close")]137 async with ConnectionPool() as http:138 response = await http.request("GET", server.url, headers=headers)139 await response.aread()140 assert len(http.active_connections) == 0141 assert len(http.keepalive_connections) == 0142143144@pytest.mark.usefixtures("async_environment")145async def test_standard_response_close(server):146 """147 A standard close should keep the connection open.148 """149 async with ConnectionPool() as http:150 response = await http.request("GET", server.url)151 await response.aread()152 await response.aclose()153 assert len(http.active_connections) == 0154 assert len(http.keepalive_connections) == 1155156157@pytest.mark.usefixtures("async_environment")158async def test_premature_response_close(server):159 """160 A premature close should close the connection.161 """162 async with ConnectionPool() as http:163 response = await http.request("GET", server.url)164 await response.aclose()165 assert len(http.active_connections) == 0166 assert len(http.keepalive_connections) == 0167168169@pytest.mark.usefixtures("async_environment")170async def test_keepalive_connection_closed_by_server_is_reestablished(server):171 """172 Upon keep-alive connection closed by remote a new connection173 should be reestablished.174 """175 async with ConnectionPool() as http:176 response = await http.request("GET", server.url)177 await response.aread()178179 # Shutdown the server to close the keep-alive connection180 await server.restart()181182 response = await http.request("GET", server.url)183 await response.aread()184 assert len(http.active_connections) == 0185 assert len(http.keepalive_connections) == 1186187188@pytest.mark.usefixtures("async_environment")189async def test_keepalive_http2_connection_closed_by_server_is_reestablished(server):190 """191 Upon keep-alive connection closed by remote a new connection192 should be reestablished.193 """194 async with ConnectionPool() as http:195 response = await http.request("GET", server.url)196 await response.aread()197198 # Shutdown the server to close the keep-alive connection199 await server.restart()200201 response = await http.request("GET", server.url)202 await response.aread()203 assert len(http.active_connections) == 0204 assert len(http.keepalive_connections) == 1205206207@pytest.mark.usefixtures("async_environment")208async def test_connection_closed_free_semaphore_on_acquire(server):209 """210 Verify that max_connections semaphore is released211 properly on a disconnected connection.212 """213 async with ConnectionPool(pool_limits=httpx.PoolLimits(hard_limit=1)) as http:214 response = await http.request("GET", server.url)215 await response.aread()216217 # Close the connection so we're forced to recycle it218 await server.restart()219220 response = await http.request("GET", server.url)221 assert response.status_code == 200222223224@pytest.mark.usefixtures("async_environment")225async def test_connection_pool_closed_close_keepalive_and_free_semaphore(server):226 """227 Closing the connection pool should close remaining keepalive connections and228 release the max_connections semaphore.229 """230 http = ConnectionPool(pool_limits=httpx.PoolLimits(hard_limit=1))231232 async with http:233 response = await http.request("GET", server.url)234 await response.aread()235 assert response.status_code == 200236 assert len(http.keepalive_connections) == 1237238 assert len(http.keepalive_connections) == 0239240 # Perform a second round of requests to make sure the max_connections semaphore241 # was released properly.242243 async with http:244 response = await http.request("GET", server.url)245 await response.aread()246 assert response.status_code == 200
deleted:tests/dispatch/test_connections.py-44 removed
1import pytest23import httpx4from httpx._config import SSLConfig5from httpx._dispatch.connection import HTTPConnection678@pytest.mark.usefixtures("async_environment")9async def test_get(server):10 async with HTTPConnection(origin=server.url) as conn:11 response = await conn.request("GET", server.url)12 await response.aread()13 assert response.status_code == 20014 assert response.content == b"Hello, world!"151617@pytest.mark.usefixtures("async_environment")18async def test_post(server):19 async with HTTPConnection(origin=server.url) as conn:20 response = await conn.request("GET", server.url, data=b"Hello, world!")21 assert response.status_code == 200222324@pytest.mark.usefixtures("async_environment")25async def test_premature_close(server):26 with pytest.raises(httpx.ConnectionClosed):27 async with HTTPConnection(origin=server.url) as conn:28 response = await conn.request(29 "GET", server.url.copy_with(path="/premature_close")30 )31 await response.aread()323334@pytest.mark.usefixtures("async_environment")35async def test_https_get_with_ssl(https_server, ca_cert_pem_file):36 """37 An HTTPS request, with SSL configuration set on the client.38 """39 ssl = SSLConfig(verify=ca_cert_pem_file)40 async with HTTPConnection(origin=https_server.url, ssl=ssl) as conn:41 response = await conn.request("GET", https_server.url)42 await response.aread()43 assert response.status_code == 20044 assert response.content == b"Hello, world!"
deleted:tests/dispatch/test_http2.py-158 removed
1import json2import socket34import h2.connection5import h2.events6import pytest7from h2.settings import SettingCodes89from httpx import AsyncClient, Response, TimeoutException10from httpx._dispatch.connection_pool import ConnectionPool1112from .utils import MockHTTP2Backend131415async def app(request):16 method = request.method17 path = request.url.path18 body = b"".join([part async for part in request.stream])19 content = json.dumps(20 {"method": method, "path": path, "body": body.decode()}21 ).encode()22 headers = {"Content-Length": str(len(content))}23 return Response(200, headers=headers, content=content, request=request)242526@pytest.mark.asyncio27async def test_http2_get_request():28 backend = MockHTTP2Backend(app=app)29 dispatch = ConnectionPool(backend=backend, http2=True)3031 async with AsyncClient(dispatch=dispatch) as client:32 response = await client.get("http://example.org")3334 assert response.status_code == 20035 assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}363738@pytest.mark.asyncio39async def test_http2_post_request():40 backend = MockHTTP2Backend(app=app)41 dispatch = ConnectionPool(backend=backend, http2=True)4243 async with AsyncClient(dispatch=dispatch) as client:44 response = await client.post("http://example.org", data=b"<data>")4546 assert response.status_code == 20047 assert json.loads(response.content) == {48 "method": "POST",49 "path": "/",50 "body": "<data>",51 }525354@pytest.mark.asyncio55async def test_http2_large_post_request():56 backend = MockHTTP2Backend(app=app)57 dispatch = ConnectionPool(backend=backend, http2=True)5859 data = b"a" * 10000060 async with AsyncClient(dispatch=dispatch) as client:61 response = await client.post("http://example.org", data=data)62 assert response.status_code == 20063 assert json.loads(response.content) == {64 "method": "POST",65 "path": "/",66 "body": data.decode(),67 }686970@pytest.mark.asyncio71async def test_http2_multiple_requests():72 backend = MockHTTP2Backend(app=app)73 dispatch = ConnectionPool(backend=backend, http2=True)7475 async with AsyncClient(dispatch=dispatch) as client:76 response_1 = await client.get("http://example.org/1")77 response_2 = await client.get("http://example.org/2")78 response_3 = await client.get("http://example.org/3")7980 assert response_1.status_code == 20081 assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}8283 assert response_2.status_code == 20084 assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}8586 assert response_3.status_code == 20087 assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}888990@pytest.mark.asyncio91async def test_http2_reconnect():92 """93 If a connection has been dropped between requests, then we should94 be seemlessly reconnected.95 """96 backend = MockHTTP2Backend(app=app)97 dispatch = ConnectionPool(backend=backend, http2=True)9899 async with AsyncClient(dispatch=dispatch) as client:100 response_1 = await client.get("http://example.org/1")101 backend.server.close_connection = True102 response_2 = await client.get("http://example.org/2")103104 assert response_1.status_code == 200105 assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}106107 assert response_2.status_code == 200108 assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}109110111@pytest.mark.asyncio112async def test_http2_settings_in_handshake():113 backend = MockHTTP2Backend(app=app)114 dispatch = ConnectionPool(backend=backend, http2=True)115116 async with AsyncClient(dispatch=dispatch) as client:117 await client.get("http://example.org")118119 h2_conn = backend.server.conn120121 assert isinstance(h2_conn, h2.connection.H2Connection)122 expected_settings = {123 SettingCodes.HEADER_TABLE_SIZE: 4096,124 SettingCodes.ENABLE_PUSH: 0,125 SettingCodes.MAX_CONCURRENT_STREAMS: 100,126 SettingCodes.INITIAL_WINDOW_SIZE: 65535,127 SettingCodes.MAX_FRAME_SIZE: 16384,128 SettingCodes.MAX_HEADER_LIST_SIZE: 65536,129 # This one's here because h2 helpfully populates remote_settings130 # with default values even if the peer doesn't send the setting.131 SettingCodes.ENABLE_CONNECT_PROTOCOL: 0,132 }133 assert dict(h2_conn.remote_settings) == expected_settings134135 # We don't expect the ENABLE_CONNECT_PROTOCOL to be in the handshake136 expected_settings.pop(SettingCodes.ENABLE_CONNECT_PROTOCOL)137138 assert len(backend.server.settings_changed) == 1139 settings = backend.server.settings_changed[0]140141 assert isinstance(settings, h2.events.RemoteSettingsChanged)142 assert len(settings.changed_settings) == len(expected_settings)143 for setting_code, changed_setting in settings.changed_settings.items():144 assert isinstance(changed_setting, h2.settings.ChangedSetting)145 assert changed_setting.new_value == expected_settings[setting_code]146147148@pytest.mark.usefixtures("async_environment")149async def test_http2_live_request():150 async with AsyncClient(http2=True) as client:151 try:152 resp = await client.get("https://nghttp2.org/httpbin/anything")153 except TimeoutException: # pragma: nocover154 pytest.xfail(reason="nghttp2.org appears to be unresponsive")155 except socket.gaierror: # pragma: nocover156 pytest.xfail(reason="You appear to be offline")157 assert resp.status_code == 200158 assert resp.http_version == "HTTP/2"
deleted:tests/dispatch/test_proxy_http.py-207 removed
1import pytest23import httpx4from httpx._dispatch.proxy_http import HTTPProxy56from .utils import MockRawSocketBackend789@pytest.mark.asyncio10async def test_proxy_tunnel_success():11 raw_io = MockRawSocketBackend(12 data_to_send=(13 [14 b"HTTP/1.1 200 OK\r\n"15 b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"16 b"Server: proxy-server\r\n"17 b"\r\n",18 b"HTTP/1.1 404 Not Found\r\n"19 b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"20 b"Server: origin-server\r\n"21 b"\r\n",22 ]23 ),24 )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")2930 assert response.status_code == 40431 assert response.headers["Server"] == "origin-server"3233 assert response.request.method == "GET"34 assert response.request.url == "http://example.com"35 assert response.request.headers["Host"] == "example.com"3637 recv = raw_io.received_data38 assert len(recv) == 339 assert recv[0] == b"--- CONNECT(127.0.0.1, 8000) ---"40 assert recv[1].startswith(41 b"CONNECT example.com:80 HTTP/1.1\r\nhost: 127.0.0.1:8000\r\n"42 )43 assert recv[2].startswith(b"GET / HTTP/1.1\r\nhost: example.com\r\n")444546@pytest.mark.asyncio47@pytest.mark.parametrize("status_code", [300, 304, 308, 401, 500])48async def test_proxy_tunnel_non_2xx_response(status_code):49 raw_io = MockRawSocketBackend(50 data_to_send=(51 [52 b"HTTP/1.1 %d Not Good\r\n" % status_code,53 b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"54 b"Server: proxy-server\r\n"55 b"\r\n",56 ]57 ),58 )5960 with pytest.raises(httpx.ProxyError) as e: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")6566 # ProxyError.request should be the CONNECT request not the original request67 assert e.value.request.method == "CONNECT"68 assert e.value.request.headers["Host"] == "127.0.0.1:8000"69 assert e.value.request.url.full_path == "example.com:80"7071 # ProxyError.response should be the CONNECT response72 assert e.value.response.status_code == status_code73 assert e.value.response.headers["Server"] == "proxy-server"7475 # Verify that the request wasn't sent after receiving an error from CONNECT76 recv = raw_io.received_data77 assert len(recv) == 278 assert recv[0] == b"--- CONNECT(127.0.0.1, 8000) ---"79 assert recv[1].startswith(80 b"CONNECT example.com:80 HTTP/1.1\r\nhost: 127.0.0.1:8000\r\n"81 )828384@pytest.mark.asyncio85async def test_proxy_tunnel_start_tls():86 raw_io = MockRawSocketBackend(87 data_to_send=(88 [89 # Tunnel Response90 b"HTTP/1.1 200 OK\r\n"91 b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"92 b"Server: proxy-server\r\n"93 b"\r\n",94 # Response 195 b"HTTP/1.1 404 Not Found\r\n"96 b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"97 b"Server: origin-server\r\n"98 b"Connection: keep-alive\r\n"99 b"Content-Length: 0\r\n"100 b"\r\n",101 # Response 2102 b"HTTP/1.1 200 OK\r\n"103 b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"104 b"Server: origin-server\r\n"105 b"Connection: keep-alive\r\n"106 b"Content-Length: 0\r\n"107 b"\r\n",108 ]109 ),110 )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")115116 assert resp.status_code == 404117 assert resp.headers["Server"] == "origin-server"118119 assert resp.request.method == "GET"120 assert resp.request.url == "https://example.com"121 assert resp.request.headers["Host"] == "example.com"122123 await resp.aread()124125 # Make another request to see that the tunnel is re-used.126 resp = await proxy.request("GET", "https://example.com/target")127128 assert resp.status_code == 200129 assert resp.headers["Server"] == "origin-server"130131 assert resp.request.method == "GET"132 assert resp.request.url == "https://example.com/target"133 assert resp.request.headers["Host"] == "example.com"134135 await resp.aread()136137 recv = raw_io.received_data138 assert len(recv) == 5139 assert recv[0] == b"--- CONNECT(127.0.0.1, 8000) ---"140 assert recv[1].startswith(141 b"CONNECT example.com:443 HTTP/1.1\r\nhost: 127.0.0.1:8000\r\n"142 )143 assert recv[2] == b"--- START_TLS(example.com) ---"144 assert recv[3].startswith(b"GET / HTTP/1.1\r\nhost: example.com\r\n")145 assert recv[4].startswith(b"GET /target HTTP/1.1\r\nhost: example.com\r\n")146147148@pytest.mark.asyncio149@pytest.mark.parametrize("proxy_mode", ["FORWARD_ONLY", "DEFAULT"])150async def test_proxy_forwarding(proxy_mode):151 raw_io = MockRawSocketBackend(152 data_to_send=(153 [154 b"HTTP/1.1 200 OK\r\n"155 b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"156 b"Server: origin-server\r\n"157 b"\r\n"158 ]159 ),160 )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"},166 ) as proxy:167 response = await proxy.request(168 "GET", "http://example.com", headers={"override": "1"}169 )170171 assert response.status_code == 200172 assert response.headers["Server"] == "origin-server"173174 assert response.request.method == "GET"175 assert response.request.url == "http://127.0.0.1:8000"176 assert response.request.url.full_path == "http://example.com"177 assert response.request.headers["Host"] == "example.com"178179 recv = raw_io.received_data180 assert len(recv) == 2181 assert recv[0] == b"--- CONNECT(127.0.0.1, 8000) ---"182 assert recv[1].startswith(183 b"GET http://example.com HTTP/1.1\r\nhost: example.com\r\n"184 )185 assert b"proxy-authorization: test" in recv[1]186 assert b"override: 1" in recv[1]187188189def test_proxy_url_with_username_and_password():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():197 proxy = HTTPProxy(198 "http://127.0.0.1:1080",199 proxy_headers={"Custom": "Header"},200 proxy_mode="DEFAULT",201 )202203 assert repr(proxy) == (204 "HTTPProxy(proxy_url=URL('http://127.0.0.1:1080') "205 "proxy_headers=Headers({'custom': 'Header'}) "206 "proxy_mode='DEFAULT')"207 )
deleted:tests/dispatch/utils.py-204 removed
1import ssl2import typing34import h2.config5import h2.connection6import h2.events78from httpx import Request, Timeout9from httpx._backends.base import BaseSocketStream, lookup_backend101112class MockHTTP2Backend:13 def __init__(self, app):14 self.app = app15 self.backend = lookup_backend()16 self.server = None1718 async def open_tcp_stream(19 self,20 hostname: str,21 port: int,22 ssl_context: typing.Optional[ssl.SSLContext],23 timeout: Timeout,24 ) -> BaseSocketStream:25 self.server = MockHTTP2Server(self.app, backend=self.backend)26 return self.server2728 # Defer all other attributes and methods to the underlying backend.29 def __getattr__(self, name: str) -> typing.Any:30 return getattr(self.backend, name)313233class MockHTTP2Server(BaseSocketStream):34 def __init__(self, app, backend: MockHTTP2Backend):35 config = h2.config.H2Configuration(client_side=False)36 self.conn = h2.connection.H2Connection(config=config)37 self.app = app38 self.backend = backend39 self.buffer = b""40 self.requests = {}41 self.close_connection = False42 self.return_data = {}43 self.settings_changed = []4445 # Socket stream interface4647 def get_http_version(self) -> str:48 return "HTTP/2"4950 async def read(self, n, timeout, flag=None) -> bytes:51 send, self.buffer = self.buffer[:n], self.buffer[n:]52 return send5354 async def write(self, data: bytes, timeout) -> None:55 if not data:56 return57 events = self.conn.receive_data(data)58 self.buffer += self.conn.data_to_send()59 for event in events:60 if isinstance(event, h2.events.RequestReceived):61 self.request_received(event.headers, event.stream_id)62 elif isinstance(event, h2.events.DataReceived):63 self.receive_data(event.data, event.stream_id)64 # This should send an UPDATE_WINDOW for both the stream and the65 # connection increasing it by the amount66 # consumed keeping the flow control window constant67 flow_control_consumed = event.flow_controlled_length68 if flow_control_consumed > 0:69 self.conn.increment_flow_control_window(flow_control_consumed)70 self.buffer += self.conn.data_to_send()71 self.conn.increment_flow_control_window(72 flow_control_consumed, event.stream_id73 )74 self.buffer += self.conn.data_to_send()75 elif isinstance(event, h2.events.StreamEnded):76 await self.stream_complete(event.stream_id)77 elif isinstance(event, h2.events.RemoteSettingsChanged):78 self.settings_changed.append(event)7980 async def close(self) -> None:81 pass8283 def is_connection_dropped(self) -> bool:84 return self.close_connection8586 # Server implementation8788 def request_received(self, headers, stream_id):89 """90 Handler for when the initial part of the HTTP request is received.91 """92 if stream_id not in self.requests:93 self.requests[stream_id] = []94 self.requests[stream_id].append({"headers": headers, "data": b""})9596 def receive_data(self, data, stream_id):97 """98 Handler for when a data part of the HTTP request is received.99 """100 self.requests[stream_id][-1]["data"] += data101102 async def stream_complete(self, stream_id):103 """104 Handler for when the HTTP request is completed.105 """106 request = self.requests[stream_id].pop(0)107 if not self.requests[stream_id]:108 del self.requests[stream_id]109110 headers_dict = dict(request["headers"])111112 method = headers_dict[b":method"].decode("ascii")113 url = "%s://%s%s" % (114 headers_dict[b":scheme"].decode("ascii"),115 headers_dict[b":authority"].decode("ascii"),116 headers_dict[b":path"].decode("ascii"),117 )118 headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]119 data = request["data"]120121 # Call out to the app.122 request = Request(method, url, headers=headers, data=data)123 response = await self.app(request)124125 # Write the response to the buffer.126 status_code_bytes = str(response.status_code).encode("ascii")127 response_headers = [(b":status", status_code_bytes)] + response.headers.raw128129 self.conn.send_headers(stream_id, response_headers)130 self.buffer += self.conn.data_to_send()131 self.return_data[stream_id] = response.content132 self.send_return_data(stream_id)133134 def send_return_data(self, stream_id):135 while self.return_data[stream_id]:136 flow_control = self.conn.local_flow_control_window(stream_id)137 chunk_size = min(138 len(self.return_data[stream_id]),139 flow_control,140 self.conn.max_outbound_frame_size,141 )142 if chunk_size > 0:143 chunk, self.return_data[stream_id] = (144 self.return_data[stream_id][:chunk_size],145 self.return_data[stream_id][chunk_size:],146 )147 self.conn.send_data(stream_id, chunk)148 self.buffer += self.conn.data_to_send()149 self.conn.end_stream(stream_id)150 self.buffer += self.conn.data_to_send()151152153class MockRawSocketBackend:154 def __init__(self, data_to_send=b""):155 self.backend = lookup_backend()156 self.data_to_send = data_to_send157 self.received_data = []158 self.stream = MockRawSocketStream(self)159160 async def open_tcp_stream(161 self,162 hostname: str,163 port: int,164 ssl_context: typing.Optional[ssl.SSLContext],165 timeout: Timeout,166 ) -> BaseSocketStream:167 self.received_data.append(168 b"--- CONNECT(%s, %d) ---" % (hostname.encode(), port)169 )170 return self.stream171172 # Defer all other attributes and methods to the underlying backend.173 def __getattr__(self, name: str) -> typing.Any:174 return getattr(self.backend, name)175176177class MockRawSocketStream(BaseSocketStream):178 def __init__(self, backend: MockRawSocketBackend):179 self.backend = backend180181 async def start_tls(182 self, hostname: str, ssl_context: ssl.SSLContext, timeout: Timeout183 ) -> BaseSocketStream:184 self.backend.received_data.append(b"--- START_TLS(%s) ---" % hostname.encode())185 return MockRawSocketStream(self.backend)186187 def get_http_version(self) -> str:188 return "HTTP/1.1"189190 async def write(self, data: bytes, timeout) -> None:191 if not data:192 return193 self.backend.received_data.append(data)194195 async def read(self, n, timeout, flag=None) -> bytes:196 if not self.backend.data_to_send:197 return b""198 return self.backend.data_to_send.pop(0)199200 def is_connection_dropped(self) -> bool:201 return False202203 async def close(self) -> None:204 pass
modified:tests/conftest.py-25 removed
294 unmodified lines
295 yield from serve_in_thread(server)296297298@pytest.fixture(scope=SERVER_SCOPE)299def uds_server():300 uds = "test_server.sock"301 config = Config(app=app, lifespan="off", loop="asyncio", uds=uds)302 server = TestServer(config=config)303 yield from serve_in_thread(server)304 os.remove(uds)305306307@pytest.fixture(scope=SERVER_SCOPE)299def https_server(cert_pem_file, cert_private_key_file):300 config = Config(301 app=app,302 lifespan="off",
4 unmodified lines
307 loop="asyncio",308 )309 server = TestServer(config=config)310 yield from serve_in_thread(server)320321322@pytest.fixture(scope=SERVER_SCOPE)323def https_uds_server(cert_pem_file, cert_private_key_file):324 uds = "https_test_server.sock"325 config = Config(326 app=app,327 lifespan="off",328 ssl_certfile=cert_pem_file,329 ssl_keyfile=cert_private_key_file,330 uds=uds,331 loop="asyncio",332 )333 server = TestServer(config=config)334 yield from serve_in_thread(server)335 os.remove(uds)
modified:tests/test_concurrency.py-27 removed
55 unmodified lines
56 await stream.close()575859@pytest.mark.usefixtures("async_environment")60async def test_start_tls_on_uds_socket_stream(https_uds_server):61 backend = lookup_backend()62 ctx = SSLConfig().load_ssl_context_no_verify()63 timeout = Timeout(5)6465 stream = await backend.open_uds_stream(66 https_uds_server.config.uds, https_uds_server.url.host, None, timeout67 )6869 try:70 assert stream.is_connection_dropped() is False71 assert get_cipher(stream) is None7273 stream = await stream.start_tls(https_uds_server.url.host, ctx, timeout)74 assert stream.is_connection_dropped() is False75 assert get_cipher(stream) is not None7677 await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)7879 response = await read_response(stream, timeout, should_contain=b"Hello, world")80 assert response.startswith(b"HTTP/1.1 200 OK\r\n")8182 finally:83 await stream.close()848586@pytest.mark.usefixtures("async_environment")60async def test_concurrent_read(server):61 """62 Regression test for: https://github.com/encode/httpx/issues/52763 """
32 unmodified lines
modified:tests/test_multipart.py+19 added-12 removed
1import binascii2import cgi3import io4import os5import typing6from unittest import mock78import httpcore9import pytest1011import httpx10from httpx._config import CertTypes, TimeoutTypes, VerifyTypes11from httpx._content_streams import encode12from httpx._dispatch.base import AsyncDispatcher12from httpx._content_streams import AsyncIteratorStream, encode13from httpx._utils import format_form_param141516class MockDispatch(AsyncDispatcher):17 async def send(16class MockDispatch(httpcore.AsyncHTTPTransport):17 async def request(18 self,19 request: httpx.Request,20 verify: VerifyTypes = None,21 cert: CertTypes = None,22 timeout: TimeoutTypes = None,23 ) -> httpx.Response:24 content = b"".join([part async for part in request.stream])25 return httpx.Response(200, content=content, request=request)19 method: bytes,20 url: typing.Tuple[bytes, bytes, int, bytes],21 headers: typing.List[typing.Tuple[bytes, bytes]] = None,22 stream: httpcore.AsyncByteStream = None,23 timeout: typing.Dict[str, typing.Optional[float]] = None,24 ) -> typing.Tuple[25 bytes,26 int,27 bytes,28 typing.List[typing.Tuple[bytes, bytes]],29 httpcore.AsyncByteStream,30 ]:31 content = AsyncIteratorStream(aiterator=(part async for part in stream))32 return b"HTTP/1.1", 200, b"OK", [], content333435@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))36@pytest.mark.asyncio
169 unmodified lines
modified:tests/test_utils.py-2 removed
96 unmodified lines
97 response = await client.get(server.url)98 assert response.status_code == 20099 stderr = capsys.readouterr().err100 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr101 assert "httpx._dispatch.connection_pool" not in stderr101102103@pytest.mark.asyncio104async def test_logs_trace(server, capsys):
2 unmodified lines
107 response = await client.get(server.url)108 assert response.status_code == 200109 stderr = capsys.readouterr().err110 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr112 assert "httpx._dispatch.connection_pool" in stderr111112113@pytest.mark.asyncio114async def test_logs_redirect_chain(server, capsys):
171 unmodified lines
modified:setup.cfg+1 added-1 removed
9 unmodified lines
10combine_as_imports = True11force_grid_wrap = 012include_trailing_comma = True13known_first_party = httpx,tests14known_third_party = brotli,certifi,chardet,cryptography,h11,h2,hstspreload,pytest,rfc3986,setuptools,sniffio,trio,trustme,urllib3,uvicorn14known_third_party = brotli,certifi,chardet,cryptography,hstspreload,httpcore,pytest,rfc3986,setuptools,sniffio,trio,trustme,urllib3,uvicorn15line_length = 8816multi_line_output = 31718[tool:pytest]
3 unmodified lines
modified:setup.py+1 added-4 removed
56 unmodified lines
57 install_requires=[58 "certifi",59 "hstspreload",60 "chardet==3.*",61 "h11>=0.8,<0.10",62 "h2==3.*",61 "idna==2.*",62 "rfc3986>=1.3,<2",65 "sniffio==1.*",66 "urllib3==1.*",63 "httpcore==0.7.*",64 ],65 classifiers=[66 "Development Status :: 4 - Beta",67 "Environment :: Web Environment",
13 unmodified lines