Merge branch 'master' into wait-for-connection-close
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by GitHub · parents 99dc1a9, 302fe93 · Browse files · 45 files·+3214 added−1106 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
45 files+3214 added−1106 removed
- tests:+1077 added−465 removed
- other:+2137 added−641 removed
Provenance
- Commit
20bc1f3- Tree
a794f5b- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent 1
99dc1a9- Parent 2
302fe93
45 files changed+3214 added−1106 removed
added:httpcore/adapters/__init__.py+4 added
1+"""2+Adapter classes layer additional behavior over the raw dispatching of the3+HTTP request/response.4+"""added:httpcore/adapters/authentication.py+18 added
1+import typing2+3+from ..interfaces import Adapter4+from ..models import Request, Response5+6+7+class AuthenticationAdapter(Adapter):8+ def __init__(self, dispatch: Adapter):9+ self.dispatch = dispatch10+11+ def prepare_request(self, request: Request) -> None:12+ self.dispatch.prepare_request(request)13+14+ async def send(self, request: Request, **options: typing.Any) -> Response:15+ return await self.dispatch.send(request, **options)16+17+ async def close(self) -> None:18+ await self.dispatch.close()added:httpcore/adapters/cookies.py+18 added
1+import typing2+3+from ..interfaces import Adapter4+from ..models import Request, Response5+6+7+class CookieAdapter(Adapter):8+ def __init__(self, dispatch: Adapter):9+ self.dispatch = dispatch10+11+ def prepare_request(self, request: Request) -> None:12+ self.dispatch.prepare_request(request)13+14+ async def send(self, request: Request, **options: typing.Any) -> Response:15+ return await self.dispatch.send(request, **options)16+17+ async def close(self) -> None:18+ await self.dispatch.close()added:httpcore/adapters/environment.py+27 added
1+import typing2+3+from ..interfaces import Adapter4+from ..models import Request, Response5+6+7+class EnvironmentAdapter(Adapter):8+ def __init__(self, dispatch: Adapter, trust_env: bool = True):9+ self.dispatch = dispatch10+ self.trust_env = trust_env11+12+ def prepare_request(self, request: Request) -> None:13+ self.dispatch.prepare_request(request)14+15+ async def send(self, request: Request, **options: typing.Any) -> Response:16+ if self.trust_env:17+ self.merge_environment_options(options)18+ return await self.dispatch.send(request, **options)19+20+ async def close(self) -> None:21+ await self.dispatch.close()22+23+ def merge_environment_options(self, options: dict) -> None:24+ """25+ Add environment options.26+ """27+ # TODOadded:httpcore/adapters/redirects.py+131 added
1+import typing2+3+from ..config import DEFAULT_MAX_REDIRECTS4+from ..exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects5+from ..interfaces import Adapter6+from ..models import URL, Headers, Request, Response7+from ..status_codes import codes8+9+10+class RedirectAdapter(Adapter):11+ def __init__(self, dispatch: Adapter, max_redirects: int = DEFAULT_MAX_REDIRECTS):12+ self.dispatch = dispatch13+ self.max_redirects = max_redirects14+15+ def prepare_request(self, request: Request) -> None:16+ self.dispatch.prepare_request(request)17+18+ async def send(self, request: Request, **options: typing.Any) -> Response:19+ allow_redirects = options.pop("allow_redirects", True) # type: bool20+21+ # The following will not typically be specified by the end-user developer,22+ # but are included in `response.next()` calls.23+ history = options.pop("history", []) # type: typing.List[Response]24+ seen_urls = options.pop("seen_urls", set()) # type: typing.Set[URL]25+26+ while True:27+ # We perform these checks here, so that calls to `response.next()`28+ # will raise redirect errors if appropriate.29+ if len(history) > self.max_redirects:30+ raise TooManyRedirects()31+ if request.url in seen_urls:32+ raise RedirectLoop()33+34+ response = await self.dispatch.send(request, **options)35+ response.history = list(history)36+ if not response.is_redirect:37+ break38+39+ history.insert(0, response)40+ seen_urls.add(request.url)41+42+ if allow_redirects:43+ request = self.build_redirect_request(request, response)44+ else:45+ next_options = dict(options)46+ next_options["seen_urls"] = seen_urls47+ next_options["history"] = history48+49+ async def send_next() -> Response:50+ nonlocal request, response, next_options51+ request = self.build_redirect_request(request, response)52+ response = await self.send(request, **next_options)53+ return response54+55+ response.next = send_next # type: ignore56+ break57+58+ return response59+60+ async def close(self) -> None:61+ await self.dispatch.close()62+63+ def build_redirect_request(self, request: Request, response: Response) -> Request:64+ method = self.redirect_method(request, response)65+ url = self.redirect_url(request, response)66+ headers = self.redirect_headers(request, url)67+ content = self.redirect_content(request, method)68+ return Request(method=method, url=url, headers=headers, content=content)69+70+ def redirect_method(self, request: Request, response: Response) -> str:71+ """72+ When being redirected we may want to change the method of the request73+ based on certain specs or browser behavior.74+ """75+ method = request.method76+77+ # https://tools.ietf.org/html/rfc7231#section-6.4.478+ if response.status_code == codes.see_other and method != "HEAD":79+ method = "GET"80+81+ # Do what the browsers do, despite standards...82+ # Turn 302s into GETs.83+ if response.status_code == codes.found and method != "HEAD":84+ method = "GET"85+86+ # If a POST is responded to with a 301, turn it into a GET.87+ # This bizarre behaviour is explained in 'requests' issue 1704.88+ if response.status_code == codes.moved_permanently and method == "POST":89+ method = "GET"90+91+ return method92+93+ def redirect_url(self, request: Request, response: Response) -> URL:94+ """95+ Return the URL for the redirect to follow.96+ """97+ location = response.headers["Location"]98+99+ url = URL(location, allow_relative=True)100+101+ # Facilitate relative 'location' headers, as allowed by RFC 7231.102+ # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')103+ # Compliant with RFC3986, we percent encode the url.104+ if not url.is_absolute:105+ url = url.resolve_with(request.url.copy_with(fragment=None))106+107+ # Attach previous fragment if needed (RFC 7231 7.1.2)108+ if request.url.fragment and not url.fragment:109+ url = url.copy_with(fragment=request.url.fragment)110+111+ return url112+113+ def redirect_headers(self, request: Request, url: URL) -> Headers:114+ """115+ Strip Authorization headers when responses are redirected away from116+ the origin.117+ """118+ headers = Headers(request.headers)119+ if url.origin != request.url.origin:120+ del headers["Authorization"]121+ return headers122+123+ def redirect_content(self, request: Request, method: str) -> bytes:124+ """125+ Return the body that should be used for the redirect request.126+ """127+ if method != request.method and method == "GET":128+ return b""129+ if request.is_streaming:130+ raise RedirectBodyUnavailable()131+ return request.contentadded:httpcore/dispatch/__init__.py+4 added
1+"""2+Dispatch classes handle the raw network connections and the implementation3+details of making the HTTP request and receiving the response.4+"""added:httpcore/dispatch/connection_pool.py+158 added
1+import collections.abc2+import typing3+4+from ..config import (5+ DEFAULT_CA_BUNDLE_PATH,6+ DEFAULT_POOL_LIMITS,7+ DEFAULT_SSL_CONFIG,8+ DEFAULT_TIMEOUT_CONFIG,9+ PoolLimits,10+ SSLConfig,11+ TimeoutConfig,12+)13+from ..decoders import ACCEPT_ENCODING14+from ..exceptions import PoolTimeout15+from ..interfaces import Adapter16+from ..models import Origin, Request, Response17+from ..streams import PoolSemaphore18+from .connection import HTTPConnection19+20+CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]21+22+23+class ConnectionStore(collections.abc.Sequence):24+ """25+ We need to maintain collections of connections in a way that allows us to:26+27+ * Lookup connections by origin.28+ * Iterate over connections by insertion time.29+ * Return the total number of connections.30+ """31+32+ def __init__(self) -> None:33+ self.all = {} # type: typing.Dict[HTTPConnection, float]34+ self.by_origin = (35+ {}36+ ) # type: typing.Dict[Origin, typing.Dict[HTTPConnection, float]]37+38+ def pop_by_origin(39+ self, origin: Origin, http2_only: bool = False40+ ) -> typing.Optional[HTTPConnection]:41+ try:42+ connections = self.by_origin[origin]43+ except KeyError:44+ return None45+46+ connection = next(reversed(list(connections.keys())))47+ if http2_only and not connection.is_http2:48+ return None49+50+ del connections[connection]51+ if not connections:52+ del self.by_origin[origin]53+ del self.all[connection]54+55+ return connection56+57+ def add(self, connection: HTTPConnection) -> None:58+ self.all[connection] = 0.059+ try:60+ self.by_origin[connection.origin][connection] = 0.061+ except KeyError:62+ self.by_origin[connection.origin] = {connection: 0.0}63+64+ def remove(self, connection: HTTPConnection) -> None:65+ del self.all[connection]66+ del self.by_origin[connection.origin][connection]67+ if not self.by_origin[connection.origin]:68+ del self.by_origin[connection.origin]69+70+ def clear(self) -> None:71+ self.all.clear()72+ self.by_origin.clear()73+74+ def __iter__(self) -> typing.Iterator[HTTPConnection]:75+ return iter(self.all.keys())76+77+ def __getitem__(self, key: typing.Any) -> typing.Any:78+ if key in self.all:79+ return key80+ return None81+82+ def __len__(self) -> int:83+ return len(self.all)84+85+86+class ConnectionPool(Adapter):87+ def __init__(88+ self,89+ *,90+ ssl: SSLConfig = DEFAULT_SSL_CONFIG,91+ timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,92+ limits: PoolLimits = DEFAULT_POOL_LIMITS,93+ ):94+ self.ssl = ssl95+ self.timeout = timeout96+ self.limits = limits97+ self.is_closed = False98+99+ self.max_connections = PoolSemaphore(limits)100+ self.keepalive_connections = ConnectionStore()101+ self.active_connections = ConnectionStore()102+103+ @property104+ def num_connections(self) -> int:105+ return len(self.keepalive_connections) + len(self.active_connections)106+107+ def prepare_request(self, request: Request) -> None:108+ request.prepare()109+110+ async def send(self, request: Request, **options: typing.Any) -> Response:111+ connection = await self.acquire_connection(request.url.origin)112+ try:113+ response = await connection.send(request, **options)114+ except BaseException as exc:115+ self.active_connections.remove(connection)116+ self.max_connections.release()117+ raise exc118+ return response119+120+ async def acquire_connection(self, origin: Origin) -> HTTPConnection:121+ connection = self.active_connections.pop_by_origin(origin, http2_only=True)122+ if connection is None:123+ connection = self.keepalive_connections.pop_by_origin(origin)124+125+ if connection is None:126+ await self.max_connections.acquire()127+ connection = HTTPConnection(128+ origin,129+ ssl=self.ssl,130+ timeout=self.timeout,131+ release_func=self.release_connection,132+ )133+134+ self.active_connections.add(connection)135+136+ return connection137+138+ async def release_connection(self, connection: HTTPConnection) -> None:139+ if connection.is_closed:140+ self.active_connections.remove(connection)141+ self.max_connections.release()142+ elif (143+ self.limits.soft_limit is not None144+ and self.num_connections > self.limits.soft_limit145+ ):146+ self.active_connections.remove(connection)147+ self.max_connections.release()148+ await connection.close()149+ else:150+ self.active_connections.remove(connection)151+ self.keepalive_connections.add(connection)152+153+ async def close(self) -> None:154+ self.is_closed = True155+ connections = list(self.keepalive_connections)156+ self.keepalive_connections.clear()157+ for connection in connections:158+ await connection.close()added:httpcore/dispatch/connection.py+93 added
1+import functools2+import typing3+4+import h2.connection5+import h116+7+from ..config import (8+ DEFAULT_SSL_CONFIG,9+ DEFAULT_TIMEOUT_CONFIG,10+ SSLConfig,11+ TimeoutConfig,12+)13+from ..exceptions import ConnectTimeout14+from ..interfaces import Adapter15+from ..models import Origin, Request, Response16+from ..streams import Protocol, connect17+from .http2 import HTTP2Connection18+from .http11 import HTTP11Connection19+20+# Callback signature: async def callback(conn: HTTPConnection) -> None21+ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]22+23+24+class HTTPConnection(Adapter):25+ def __init__(26+ self,27+ origin: typing.Union[str, Origin],28+ ssl: SSLConfig = DEFAULT_SSL_CONFIG,29+ timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,30+ release_func: typing.Optional[ReleaseCallback] = None,31+ ):32+ self.origin = Origin(origin) if isinstance(origin, str) else origin33+ self.ssl = ssl34+ self.timeout = timeout35+ self.release_func = release_func36+ self.h11_connection = None # type: typing.Optional[HTTP11Connection]37+ self.h2_connection = None # type: typing.Optional[HTTP2Connection]38+39+ def prepare_request(self, request: Request) -> None:40+ request.prepare()41+42+ async def send(self, request: Request, **options: typing.Any) -> Response:43+ if self.h11_connection is None and self.h2_connection is None:44+ await self.connect(**options)45+46+ if self.h2_connection is not None:47+ response = await self.h2_connection.send(request, **options)48+ else:49+ assert self.h11_connection is not None50+ response = await self.h11_connection.send(request, **options)51+52+ return response53+54+ async def connect(self, **options: typing.Any) -> None:55+ ssl = options.get("ssl", self.ssl)56+ timeout = options.get("timeout", self.timeout)57+ assert isinstance(ssl, SSLConfig)58+ assert isinstance(timeout, TimeoutConfig)59+60+ host = self.origin.host61+ port = self.origin.port62+ ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None63+64+ if self.release_func is None:65+ on_release = None66+ else:67+ on_release = functools.partial(self.release_func, self)68+69+ reader, writer, protocol = await connect(host, port, ssl_context, timeout)70+ if protocol == Protocol.HTTP_2:71+ self.h2_connection = HTTP2Connection(reader, writer, on_release=on_release)72+ else:73+ self.h11_connection = HTTP11Connection(74+ reader, writer, on_release=on_release75+ )76+77+ async def close(self) -> None:78+ if self.h2_connection is not None:79+ await self.h2_connection.close()80+ elif self.h11_connection is not None:81+ await self.h11_connection.close()82+83+ @property84+ def is_http2(self) -> bool:85+ return self.h2_connection is not None86+87+ @property88+ def is_closed(self) -> bool:89+ if self.h2_connection is not None:90+ return self.h2_connection.is_closed91+ else:92+ assert self.h11_connection is not None93+ return self.h11_connection.is_closedadded:httpcore/dispatch/http11.py+148 added
1+import typing2+3+import h114+5+from ..config import (6+ DEFAULT_SSL_CONFIG,7+ DEFAULT_TIMEOUT_CONFIG,8+ SSLConfig,9+ TimeoutConfig,10+)11+from ..exceptions import ConnectTimeout, ReadTimeout12+from ..interfaces import Adapter13+from ..models import Request, Response14+from ..streams import BaseReader, BaseWriter15+16+H11Event = typing.Union[17+ h11.Request,18+ h11.Response,19+ h11.InformationalResponse,20+ h11.Data,21+ h11.EndOfMessage,22+ h11.ConnectionClosed,23+]24+25+26+OptionalTimeout = typing.Optional[TimeoutConfig]27+28+# Callback signature: async def callback() -> None29+# In practice the callback will be a functools partial, which binds30+# the `ConnectionPool.release_connection(conn: HTTPConnection)` method.31+OnReleaseCallback = typing.Callable[[], typing.Awaitable[None]]32+33+34+class HTTP11Connection(Adapter):35+ READ_NUM_BYTES = 409636+37+ def __init__(38+ self,39+ reader: BaseReader,40+ writer: BaseWriter,41+ on_release: typing.Optional[OnReleaseCallback] = None,42+ ):43+ self.reader = reader44+ self.writer = writer45+ self.on_release = on_release46+ self.h11_state = h11.Connection(our_role=h11.CLIENT)47+48+ def prepare_request(self, request: Request) -> None:49+ request.prepare()50+51+ async def send(self, request: Request, **options: typing.Any) -> Response:52+ timeout = options.get("timeout")53+ stream = options.get("stream", False)54+ assert timeout is None or isinstance(timeout, TimeoutConfig)55+56+ # Start sending the request.57+ method = request.method.encode()58+ target = request.url.full_path59+ headers = request.headers.raw60+ event = h11.Request(method=method, target=target, headers=headers)61+ await self._send_event(event, timeout)62+63+ # Send the request body.64+ async for data in request.stream():65+ event = h11.Data(data=data)66+ await self._send_event(event, timeout)67+68+ # Finalize sending the request.69+ event = h11.EndOfMessage()70+ await self._send_event(event, timeout)71+72+ # Start getting the response.73+ event = await self._receive_event(timeout)74+ if isinstance(event, h11.InformationalResponse):75+ event = await self._receive_event(timeout)76+77+ assert isinstance(event, h11.Response)78+ reason_phrase = event.reason.decode("latin1")79+ status_code = event.status_code80+ headers = event.headers81+ content = self._body_iter(timeout)82+83+ response = Response(84+ status_code=status_code,85+ reason_phrase=reason_phrase,86+ protocol="HTTP/1.1",87+ headers=headers,88+ content=content,89+ on_close=self.response_closed,90+ request=request,91+ )92+93+ if not stream:94+ try:95+ await response.read()96+ finally:97+ await response.close()98+99+ return response100+101+ async def close(self) -> None:102+ event = h11.ConnectionClosed()103+ try:104+ # If we're in h11.MUST_CLOSE then we'll end up in h11.CLOSED.105+ self.h11_state.send(event)106+ except h11.ProtocolError:107+ # If we're in some other state then it's a premature close,108+ # and we'll end up in h11.ERROR.109+ pass110+111+ await self.writer.close()112+113+ async def _body_iter(self, timeout: OptionalTimeout) -> typing.AsyncIterator[bytes]:114+ event = await self._receive_event(timeout)115+ while isinstance(event, h11.Data):116+ yield event.data117+ event = await self._receive_event(timeout)118+ assert isinstance(event, h11.EndOfMessage)119+120+ async def _send_event(self, event: H11Event, timeout: OptionalTimeout) -> None:121+ data = self.h11_state.send(event)122+ await self.writer.write(data, timeout)123+124+ async def _receive_event(self, timeout: OptionalTimeout) -> H11Event:125+ event = self.h11_state.next_event()126+127+ while event is h11.NEED_DATA:128+ data = await self.reader.read(self.READ_NUM_BYTES, timeout)129+ self.h11_state.receive_data(data)130+ event = self.h11_state.next_event()131+132+ return event133+134+ async def response_closed(self) -> None:135+ if (136+ self.h11_state.our_state is h11.DONE137+ and self.h11_state.their_state is h11.DONE138+ ):139+ self.h11_state.start_next_cycle()140+ else:141+ await self.close()142+143+ if self.on_release is not None:144+ await self.on_release()145+146+ @property147+ def is_closed(self) -> bool:148+ return self.h11_state.our_state in (h11.CLOSED, h11.ERROR)added:httpcore/dispatch/http2.py+156 added
1+import functools2+import typing3+4+import h2.connection5+import h2.events6+7+from ..config import (8+ DEFAULT_SSL_CONFIG,9+ DEFAULT_TIMEOUT_CONFIG,10+ SSLConfig,11+ TimeoutConfig,12+)13+from ..exceptions import ConnectTimeout, ReadTimeout14+from ..interfaces import Adapter15+from ..models import Request, Response16+from ..streams import BaseReader, BaseWriter17+18+OptionalTimeout = typing.Optional[TimeoutConfig]19+20+21+class HTTP2Connection(Adapter):22+ READ_NUM_BYTES = 409623+24+ def __init__(25+ self, reader: BaseReader, writer: BaseWriter, on_release: typing.Callable = None26+ ):27+ self.reader = reader28+ self.writer = writer29+ self.on_release = on_release30+ self.h2_state = h2.connection.H2Connection()31+ self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]32+ self.initialized = False33+34+ def prepare_request(self, request: Request) -> None:35+ request.prepare()36+37+ async def send(self, request: Request, **options: typing.Any) -> Response:38+ timeout = options.get("timeout")39+ stream = options.get("stream", False)40+ assert timeout is None or isinstance(timeout, TimeoutConfig)41+42+ # Start sending the request.43+ if not self.initialized:44+ self.initiate_connection()45+ stream_id = await self.send_headers(request, timeout)46+ self.events[stream_id] = []47+48+ # Send the request body.49+ async for data in request.stream():50+ await self.send_data(stream_id, data, timeout)51+52+ # Finalize sending the request.53+ await self.end_stream(stream_id, timeout)54+55+ # Start getting the response.56+ while True:57+ event = await self.receive_event(stream_id, timeout)58+ if isinstance(event, h2.events.ResponseReceived):59+ break60+61+ status_code = 20062+ headers = []63+ for k, v in event.headers:64+ if k == b":status":65+ status_code = int(v.decode())66+ elif not k.startswith(b":"):67+ headers.append((k, v))68+69+ content = self.body_iter(stream_id, timeout)70+ on_close = functools.partial(self.response_closed, stream_id=stream_id)71+72+ response = Response(73+ status_code=status_code,74+ protocol="HTTP/2",75+ headers=headers,76+ content=content,77+ on_close=on_close,78+ request=request,79+ )80+81+ if not stream:82+ try:83+ await response.read()84+ finally:85+ await response.close()86+87+ return response88+89+ async def close(self) -> None:90+ await self.writer.close()91+92+ def initiate_connection(self) -> None:93+ self.h2_state.initiate_connection()94+ data_to_send = self.h2_state.data_to_send()95+ self.writer.write_no_block(data_to_send)96+ self.initialized = True97+98+ async def send_headers(self, request: Request, timeout: OptionalTimeout) -> int:99+ stream_id = self.h2_state.get_next_available_stream_id()100+ headers = [101+ (b":method", request.method.encode()),102+ (b":authority", request.url.host.encode()),103+ (b":scheme", request.url.scheme.encode()),104+ (b":path", request.url.full_path.encode()),105+ ] + request.headers.raw106+ self.h2_state.send_headers(stream_id, headers)107+ data_to_send = self.h2_state.data_to_send()108+ await self.writer.write(data_to_send, timeout)109+ return stream_id110+111+ async def send_data(112+ self, stream_id: int, data: bytes, timeout: OptionalTimeout113+ ) -> None:114+ self.h2_state.send_data(stream_id, data)115+ data_to_send = self.h2_state.data_to_send()116+ await self.writer.write(data_to_send, timeout)117+118+ async def end_stream(self, stream_id: int, timeout: OptionalTimeout) -> None:119+ self.h2_state.end_stream(stream_id)120+ data_to_send = self.h2_state.data_to_send()121+ await self.writer.write(data_to_send, timeout)122+123+ async def body_iter(124+ self, stream_id: int, timeout: OptionalTimeout125+ ) -> typing.AsyncIterator[bytes]:126+ while True:127+ event = await self.receive_event(stream_id, timeout)128+ if isinstance(event, h2.events.DataReceived):129+ yield event.data130+ elif isinstance(event, h2.events.StreamEnded):131+ break132+133+ async def receive_event(134+ self, stream_id: int, timeout: OptionalTimeout135+ ) -> h2.events.Event:136+ while not self.events[stream_id]:137+ data = await self.reader.read(self.READ_NUM_BYTES, timeout)138+ events = self.h2_state.receive_data(data)139+ for event in events:140+ if getattr(event, "stream_id", 0):141+ self.events[event.stream_id].append(event)142+143+ data_to_send = self.h2_state.data_to_send()144+ await self.writer.write(data_to_send, timeout)145+146+ return self.events[stream_id].pop(0)147+148+ async def response_closed(self, stream_id: int) -> None:149+ del self.events[stream_id]150+151+ if not self.events and self.on_release is not None:152+ await self.on_release()153+154+ @property155+ def is_closed(self) -> bool:156+ return Falsemodified:httpcore/__init__.py+16 added-3 removed
1+from .adapters.redirects import RedirectAdapter2+from .client import Client3 from .config import PoolLimits, SSLConfig, TimeoutConfig2-from .connectionpool import ConnectionPool3-from .datastructures import URL, Origin, Request, Response4+from .dispatch.connection import HTTPConnection5+from .dispatch.connection_pool import ConnectionPool6+from .dispatch.http2 import HTTP2Connection7+from .dispatch.http11 import HTTP11Connection8 from .exceptions import (9 ConnectTimeout,10+ DecodingError,11+ InvalidURL,12 PoolTimeout,13 ProtocolError,14 ReadTimeout,15+ RedirectBodyUnavailable,16+ RedirectLoop,17 ResponseClosed,18+ ResponseNotRead,19 StreamConsumed,20 Timeout,21+ TooManyRedirects,22 )13-from .http11 import HTTP11Connection23+from .interfaces import Adapter24+from .models import URL, Headers, Origin, Request, Response25+from .status_codes import codes26+from .streams import BaseReader, BaseWriter, Protocol, Reader, Writer, connect27 from .sync import SyncClient, SyncConnectionPool28 29 __version__ = "0.2.1"added:httpcore/client.py+244 added
1+import typing2+from types import TracebackType3+4+from .adapters.authentication import AuthenticationAdapter5+from .adapters.cookies import CookieAdapter6+from .adapters.environment import EnvironmentAdapter7+from .adapters.redirects import RedirectAdapter8+from .config import (9+ DEFAULT_MAX_REDIRECTS,10+ DEFAULT_POOL_LIMITS,11+ DEFAULT_SSL_CONFIG,12+ DEFAULT_TIMEOUT_CONFIG,13+ PoolLimits,14+ SSLConfig,15+ TimeoutConfig,16+)17+from .dispatch.connection_pool import ConnectionPool18+from .models import URL, ByteOrByteStream, HeaderTypes, Request, Response, URLTypes19+20+21+class Client:22+ def __init__(23+ self,24+ ssl: SSLConfig = DEFAULT_SSL_CONFIG,25+ timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,26+ limits: PoolLimits = DEFAULT_POOL_LIMITS,27+ max_redirects: int = DEFAULT_MAX_REDIRECTS,28+ ):29+ connection_pool = ConnectionPool(ssl=ssl, timeout=timeout, limits=limits)30+ cookie_adapter = CookieAdapter(dispatch=connection_pool)31+ auth_adapter = AuthenticationAdapter(dispatch=cookie_adapter)32+ redirect_adapter = RedirectAdapter(33+ dispatch=auth_adapter, max_redirects=max_redirects34+ )35+ self.adapter = EnvironmentAdapter(dispatch=redirect_adapter)36+37+ async def request(38+ self,39+ method: str,40+ url: URLTypes,41+ *,42+ content: ByteOrByteStream = b"",43+ headers: HeaderTypes = None,44+ stream: bool = False,45+ allow_redirects: bool = True,46+ ssl: SSLConfig = None,47+ timeout: TimeoutConfig = None,48+ ) -> Response:49+ request = Request(method, url, headers=headers, content=content)50+ self.prepare_request(request)51+ response = await self.send(52+ request,53+ stream=stream,54+ allow_redirects=allow_redirects,55+ ssl=ssl,56+ timeout=timeout,57+ )58+ return response59+60+ async def get(61+ self,62+ url: URLTypes,63+ *,64+ headers: HeaderTypes = None,65+ stream: bool = False,66+ allow_redirects: bool = True,67+ ssl: SSLConfig = None,68+ timeout: TimeoutConfig = None,69+ ) -> Response:70+ return await self.request(71+ "GET",72+ url,73+ headers=headers,74+ stream=stream,75+ allow_redirects=allow_redirects,76+ ssl=ssl,77+ timeout=timeout,78+ )79+80+ async def options(81+ self,82+ url: URLTypes,83+ *,84+ headers: HeaderTypes = None,85+ stream: bool = False,86+ allow_redirects: bool = True,87+ ssl: SSLConfig = None,88+ timeout: TimeoutConfig = None,89+ ) -> Response:90+ return await self.request(91+ "OPTIONS",92+ url,93+ headers=headers,94+ stream=stream,95+ allow_redirects=allow_redirects,96+ ssl=ssl,97+ timeout=timeout,98+ )99+100+ async def head(101+ self,102+ url: URLTypes,103+ *,104+ headers: HeaderTypes = None,105+ stream: bool = False,106+ allow_redirects: bool = False, # Note: Differs to usual default.107+ ssl: SSLConfig = None,108+ timeout: TimeoutConfig = None,109+ ) -> Response:110+ return await self.request(111+ "HEAD",112+ url,113+ headers=headers,114+ stream=stream,115+ allow_redirects=allow_redirects,116+ ssl=ssl,117+ timeout=timeout,118+ )119+120+ async def post(121+ self,122+ url: URLTypes,123+ *,124+ content: ByteOrByteStream = b"",125+ headers: HeaderTypes = None,126+ stream: bool = False,127+ allow_redirects: bool = True,128+ ssl: SSLConfig = None,129+ timeout: TimeoutConfig = None,130+ ) -> Response:131+ return await self.request(132+ "POST",133+ url,134+ content=content,135+ headers=headers,136+ stream=stream,137+ allow_redirects=allow_redirects,138+ ssl=ssl,139+ timeout=timeout,140+ )141+142+ async def put(143+ self,144+ url: URLTypes,145+ *,146+ content: ByteOrByteStream = b"",147+ headers: HeaderTypes = None,148+ stream: bool = False,149+ allow_redirects: bool = True,150+ ssl: SSLConfig = None,151+ timeout: TimeoutConfig = None,152+ ) -> Response:153+ return await self.request(154+ "PUT",155+ url,156+ content=content,157+ headers=headers,158+ stream=stream,159+ allow_redirects=allow_redirects,160+ ssl=ssl,161+ timeout=timeout,162+ )163+164+ async def patch(165+ self,166+ url: URLTypes,167+ *,168+ content: ByteOrByteStream = b"",169+ headers: HeaderTypes = None,170+ stream: bool = False,171+ allow_redirects: bool = True,172+ ssl: SSLConfig = None,173+ timeout: TimeoutConfig = None,174+ ) -> Response:175+ return await self.request(176+ "PATCH",177+ url,178+ content=content,179+ headers=headers,180+ stream=stream,181+ allow_redirects=allow_redirects,182+ ssl=ssl,183+ timeout=timeout,184+ )185+186+ async def delete(187+ self,188+ url: URLTypes,189+ *,190+ content: ByteOrByteStream = b"",191+ headers: HeaderTypes = None,192+ stream: bool = False,193+ allow_redirects: bool = True,194+ ssl: SSLConfig = None,195+ timeout: TimeoutConfig = None,196+ ) -> Response:197+ return await self.request(198+ "DELETE",199+ url,200+ content=content,201+ headers=headers,202+ stream=stream,203+ allow_redirects=allow_redirects,204+ ssl=ssl,205+ timeout=timeout,206+ )207+208+ def prepare_request(self, request: Request) -> None:209+ self.adapter.prepare_request(request)210+211+ async def send(212+ self,213+ request: Request,214+ *,215+ stream: bool = False,216+ allow_redirects: bool = True,217+ ssl: SSLConfig = None,218+ timeout: TimeoutConfig = None,219+ ) -> Response:220+ options = {221+ "stream": stream,222+ "allow_redirects": allow_redirects,223+ } # type: typing.Dict[str, typing.Any]224+225+ if ssl is not None:226+ options["ssl"] = ssl227+ if timeout is not None:228+ options["timeout"] = timeout229+230+ return await self.adapter.send(request, **options)231+232+ async def close(self) -> None:233+ await self.adapter.close()234+235+ async def __aenter__(self) -> "Client":236+ return self237+238+ async def __aexit__(239+ self,240+ exc_type: typing.Type[BaseException] = None,241+ exc_value: BaseException = None,242+ traceback: TracebackType = None,243+ ) -> None:244+ await self.close()modified:httpcore/config.py+33 added-25 removed
25 unmodified lines26 and self.cert == other.cert27 and self.verify == other.verify28 )29 30- def __hash__(self) -> int:31- as_tuple = (self.cert, self.verify)32- return hash(as_tuple)33-30 def __repr__(self) -> str:31 class_name = self.__class__.__name__32 return f"{class_name}(cert={self.cert}, verify={self.verify})"33 34 unmodified lines68 "Could not find a suitable TLS CA certificate bundle, "69 "invalid path: {}".format(self.verify)70 )71 76- context = ssl.create_default_context()72+ context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)73+74+ context.verify_mode = ssl.CERT_REQUIRED75+76+ context.options |= ssl.OP_NO_SSLv277+ context.options |= ssl.OP_NO_SSLv378+ context.options |= ssl.OP_NO_COMPRESSION79+80+ # RFC 7540 Section 9.2.2: "deployments of HTTP/2 that use TLS 1.2 MUST81+ # support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". In practice, the82+ # blacklist defined in this section allows only the AES GCM and ChaCha2083+ # cipher suites with ephemeral key negotiation.84+ context.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")85+86+ if ssl.HAS_ALPN:87+ context.set_alpn_protocols(["h2", "http/1.1"])88+ if ssl.HAS_NPN:89+ context.set_npn_protocols(["h2", "http/1.1"])90+91 if os.path.isfile(ca_bundle_path):92 context.load_verify_locations(cafile=ca_bundle_path)93 elif os.path.isdir(ca_bundle_path):94 context.load_verify_locations(capath=ca_bundle_path)17 unmodified lines112 timeout: float = None,113 *,114 connect_timeout: float = None,115 read_timeout: float = None,102- pool_timeout: float = None,116+ write_timeout: float = None,117 ):118 if timeout is not None:119 # Specified as a single timeout value120 assert connect_timeout is None121 assert read_timeout is None108- assert pool_timeout is None122+ assert write_timeout is None123 connect_timeout = timeout124 read_timeout = timeout111- pool_timeout = timeout125+ write_timeout = timeout126 127 self.timeout = timeout128 self.connect_timeout = connect_timeout129 self.read_timeout = read_timeout116- self.pool_timeout = pool_timeout130+ self.write_timeout = write_timeout131 132 def __eq__(self, other: typing.Any) -> bool:133 return (134 isinstance(other, self.__class__)135 and self.connect_timeout == other.connect_timeout136 and self.read_timeout == other.read_timeout123- and self.pool_timeout == other.pool_timeout137+ and self.write_timeout == other.write_timeout138 )139 126- def __hash__(self) -> int:127- as_tuple = (self.connect_timeout, self.read_timeout, self.pool_timeout)128- return hash(as_tuple)129-140 def __repr__(self) -> str:141 class_name = self.__class__.__name__142 if self.timeout is not None:143 return f"{class_name}(timeout={self.timeout})"134- return f"{class_name}(connect_timeout={self.connect_timeout}, read_timeout={self.read_timeout}, pool_timeout={self.pool_timeout})"144+ return f"{class_name}(connect_timeout={self.connect_timeout}, read_timeout={self.read_timeout}, write_timeout={self.write_timeout})"145 146 147 class PoolLimits:148 """2 unmodified lines151 152 def __init__(153 self,154 *,145- soft_limit: typing.Optional[int] = None,146- hard_limit: typing.Optional[int] = None,155+ soft_limit: int = None,156+ hard_limit: int = None,157+ pool_timeout: float = None,158 ):159 self.soft_limit = soft_limit160 self.hard_limit = hard_limit161+ self.pool_timeout = pool_timeout162 163 def __eq__(self, other: typing.Any) -> bool:164 return (165 isinstance(other, self.__class__)166 and self.soft_limit == other.soft_limit167 and self.hard_limit == other.hard_limit168+ and self.pool_timeout == other.pool_timeout169 )170 158- def __hash__(self) -> int:159- as_tuple = (self.soft_limit, self.hard_limit)160- return hash(as_tuple)161-171 def __repr__(self) -> str:172 class_name = self.__class__.__name__164- return (165- f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit})"166- )173+ return f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit}, pool_timeout={self.pool_timeout})"174 175 176 DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)177 DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)171-DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100)178+DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100, pool_timeout=5.0)179 DEFAULT_CA_BUNDLE_PATH = certifi.where()180+DEFAULT_MAX_REDIRECTS = 20deleted:httpcore/connectionpool.py-132 removed
1-import asyncio2-import typing3-4-from .config import (5- DEFAULT_CA_BUNDLE_PATH,6- DEFAULT_POOL_LIMITS,7- DEFAULT_SSL_CONFIG,8- DEFAULT_TIMEOUT_CONFIG,9- PoolLimits,10- SSLConfig,11- TimeoutConfig,12-)13-from .datastructures import Client, Origin, Request, Response14-from .exceptions import PoolTimeout15-from .http11 import HTTP11Connection16-17-18-class ConnectionPool(Client):19- def __init__(20- self,21- *,22- ssl: SSLConfig = DEFAULT_SSL_CONFIG,23- timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,24- limits: PoolLimits = DEFAULT_POOL_LIMITS,25- ):26- self.ssl = ssl27- self.timeout = timeout28- self.limits = limits29- self.is_closed = False30- self.num_active_connections = 031- self.num_keepalive_connections = 032- self._keepalive_connections = (33- {}34- ) # type: typing.Dict[Origin, typing.List[HTTP11Connection]]35- self._max_connections = ConnectionSemaphore(36- max_connections=self.limits.hard_limit37- )38-39- async def send(40- self,41- request: Request,42- *,43- ssl: typing.Optional[SSLConfig] = None,44- timeout: typing.Optional[TimeoutConfig] = None,45- ) -> Response:46- connection = await self.acquire_connection(request.url.origin, timeout=timeout)47- response = await connection.send(request, ssl=ssl, timeout=timeout)48- return response49-50- @property51- def num_connections(self) -> int:52- return self.num_active_connections + self.num_keepalive_connections53-54- async def acquire_connection(55- self, origin: Origin, timeout: typing.Optional[TimeoutConfig] = None56- ) -> HTTP11Connection:57- try:58- connection = self._keepalive_connections[origin].pop()59- if not self._keepalive_connections[origin]:60- del self._keepalive_connections[origin]61- self.num_keepalive_connections -= 162- self.num_active_connections += 163-64- except (KeyError, IndexError):65- if timeout is None:66- pool_timeout = self.timeout.pool_timeout67- else:68- pool_timeout = timeout.pool_timeout69-70- try:71- await asyncio.wait_for(self._max_connections.acquire(), pool_timeout)72- except asyncio.TimeoutError:73- raise PoolTimeout()74- connection = HTTP11Connection(75- origin,76- ssl=self.ssl,77- timeout=self.timeout,78- on_release=self.release_connection,79- )80- self.num_active_connections += 181-82- return connection83-84- async def release_connection(self, connection: HTTP11Connection) -> None:85- if connection.is_closed:86- self._max_connections.release()87- self.num_active_connections -= 188- elif (89- self.limits.soft_limit is not None90- and self.num_connections > self.limits.soft_limit91- ):92- self._max_connections.release()93- self.num_active_connections -= 194- await connection.close()95- else:96- self.num_active_connections -= 197- self.num_keepalive_connections += 198- try:99- self._keepalive_connections[connection.origin].append(connection)100- except KeyError:101- self._keepalive_connections[connection.origin] = [connection]102-103- async def close(self) -> None:104- self.is_closed = True105- all_connections = []106- for connections in self._keepalive_connections.values():107- all_connections.extend(list(connections))108- self._keepalive_connections.clear()109- for connection in all_connections:110- await connection.close()111-112-113-class ConnectionSemaphore:114- def __init__(self, max_connections: int = None):115- self.max_connections = max_connections116-117- @property118- def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:119- if not hasattr(self, "_semaphore"):120- if self.max_connections is None:121- self._semaphore = None122- else:123- self._semaphore = asyncio.BoundedSemaphore(value=self.max_connections)124- return self._semaphore125-126- async def acquire(self) -> None:127- if self.semaphore is not None:128- await self.semaphore.acquire()129-130- def release(self) -> None:131- if self.semaphore is not None:132- self.semaphore.release()deleted:httpcore/datastructures.py-280 removed
1-import http2-import typing3-from types import TracebackType4-from urllib.parse import urlsplit5-6-from .config import SSLConfig, TimeoutConfig7-from .decoders import (8- ACCEPT_ENCODING,9- SUPPORTED_DECODERS,10- Decoder,11- IdentityDecoder,12- MultiDecoder,13-)14-from .exceptions import ResponseClosed, StreamConsumed15-16-17-class URL:18- def __init__(self, url: str = "") -> None:19- self.components = urlsplit(url)20- if not self.components.scheme:21- raise ValueError("No scheme included in URL.")22- if self.components.scheme not in ("http", "https"):23- raise ValueError('URL scheme must be "http" or "https".')24- if not self.components.hostname:25- raise ValueError("No hostname included in URL.")26-27- @property28- def scheme(self) -> str:29- return self.components.scheme30-31- @property32- def netloc(self) -> str:33- return self.components.netloc34-35- @property36- def path(self) -> str:37- return self.components.path38-39- @property40- def query(self) -> str:41- return self.components.query42-43- @property44- def hostname(self) -> str:45- return self.components.hostname46-47- @property48- def port(self) -> int:49- port = self.components.port50- if port is None:51- return {"https": 443, "http": 80}[self.scheme]52- return port53-54- @property55- def target(self) -> str:56- path = self.path or "/"57- query = self.query58- if query:59- return path + "?" + query60- return path61-62- @property63- def is_secure(self) -> bool:64- return self.components.scheme == "https"65-66- @property67- def origin(self) -> "Origin":68- return Origin(self)69-70-71-class Origin:72- def __init__(self, url: typing.Union[str, URL]) -> None:73- if isinstance(url, str):74- url = URL(url)75- self.is_ssl = url.scheme == "https"76- self.hostname = url.hostname.lower()77- self.port = url.port78-79- def __eq__(self, other: typing.Any) -> bool:80- return (81- isinstance(other, self.__class__)82- and self.is_ssl == other.is_ssl83- and self.hostname == other.hostname84- and self.port == other.port85- )86-87- def __hash__(self) -> int:88- return hash((self.is_ssl, self.hostname, self.port))89-90-91-class Request:92- def __init__(93- self,94- method: str,95- url: typing.Union[str, URL],96- *,97- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),98- body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",99- ):100- self.method = method.upper()101- self.url = URL(url) if isinstance(url, str) else url102- self.headers = list(headers)103- if isinstance(body, bytes):104- self.is_streaming = False105- self.body = body106- else:107- self.is_streaming = True108- self.body_aiter = body109- self.headers = self._auto_headers() + self.headers110-111- def _auto_headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:112- has_host = False113- has_content_length = False114- has_accept_encoding = False115-116- for header, value in self.headers:117- header = header.strip().lower()118- if header == b"host":119- has_host = True120- elif header in (b"content-length", b"transfer-encoding"):121- has_content_length = True122- elif header == b"accept-encoding":123- has_accept_encoding = True124-125- headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]126-127- if not has_host:128- headers.append((b"host", self.url.netloc.encode("ascii")))129- if not has_content_length:130- if self.is_streaming:131- headers.append((b"transfer-encoding", b"chunked"))132- elif self.body:133- content_length = str(len(self.body)).encode()134- headers.append((b"content-length", content_length))135- if not has_accept_encoding:136- headers.append((b"accept-encoding", ACCEPT_ENCODING))137-138- return headers139-140- async def stream(self) -> typing.AsyncIterator[bytes]:141- assert self.is_streaming142-143- async for part in self.body_aiter:144- yield part145-146-147-class Response:148- def __init__(149- self,150- status_code: int,151- *,152- reason: typing.Optional[str] = None,153- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),154- body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",155- on_close: typing.Callable = None,156- ):157- self.status_code = status_code158- if not reason:159- try:160- self.reason = http.HTTPStatus(status_code).phrase161- except ValueError as exc:162- self.reason = ""163- else:164- self.reason = reason165- self.headers = list(headers)166- self.on_close = on_close167- self.is_closed = False168- self.is_streamed = False169-170- decoders = [] # type: typing.List[Decoder]171- for header, value in self.headers:172- if header.strip().lower() == b"content-encoding":173- for part in value.split(b","):174- part = part.strip().lower()175- decoder_cls = SUPPORTED_DECODERS[part]176- decoders.append(decoder_cls())177-178- if len(decoders) == 0:179- self.decoder = IdentityDecoder() # type: Decoder180- elif len(decoders) == 1:181- self.decoder = decoders[0]182- else:183- self.decoder = MultiDecoder(decoders)184-185- if isinstance(body, bytes):186- self.is_closed = True187- self.body = self.decoder.decode(body) + self.decoder.flush()188- else:189- self.body_aiter = body190-191- async def read(self) -> bytes:192- """193- Read and return the response content.194- """195- if not hasattr(self, "body"):196- body = b""197- async for part in self.stream():198- body += part199- self.body = body200- return self.body201-202- async def stream(self) -> typing.AsyncIterator[bytes]:203- """204- A byte-iterator over the decoded response content.205- This allows us to handle gzip, deflate, and brotli encoded responses.206- """207- if hasattr(self, "body"):208- yield self.body209- else:210- async for chunk in self.raw():211- yield self.decoder.decode(chunk)212- yield self.decoder.flush()213-214- async def raw(self) -> typing.AsyncIterator[bytes]:215- """216- A byte-iterator over the raw response content.217- """218- if self.is_streamed:219- raise StreamConsumed()220- if self.is_closed:221- raise ResponseClosed()222- self.is_streamed = True223- async for part in self.body_aiter:224- yield part225- await self.close()226-227- async def close(self) -> None:228- """229- Close the response and release the connection.230- Automatically called if the response body is read to completion.231- """232- if not self.is_closed:233- self.is_closed = True234- if self.on_close is not None:235- await self.on_close()236-237-238-class Client:239- async def request(240- self,241- method: str,242- url: typing.Union[str, URL],243- *,244- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),245- body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",246- ssl: typing.Optional[SSLConfig] = None,247- timeout: typing.Optional[TimeoutConfig] = None,248- stream: bool = False,249- ) -> Response:250- request = Request(method, url, headers=headers, body=body)251- response = await self.send(request, ssl=ssl, timeout=timeout)252- if not stream:253- try:254- await response.read()255- finally:256- await response.close()257- return response258-259- async def send(260- self,261- request: Request,262- *,263- ssl: typing.Optional[SSLConfig] = None,264- timeout: typing.Optional[TimeoutConfig] = None,265- ) -> Response:266- raise NotImplementedError() # pragma: nocover267-268- async def close(self) -> None:269- raise NotImplementedError() # pragma: nocover270-271- async def __aenter__(self) -> "Client":272- return self273-274- async def __aexit__(275- self,276- exc_type: typing.Type[BaseException] = None,277- exc_value: BaseException = None,278- traceback: TracebackType = None,279- ) -> None:280- await self.close()modified:httpcore/decoders.py+35 added-15 removed
4 unmodified lines5 """6 import typing7 import zlib8 9+import httpcore.exceptions10+11 try:12 import brotli13 except ImportError: # pragma: nocover14 brotli = None25 unmodified lines40 def __init__(self) -> None:41 self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)42 43 def decode(self, data: bytes) -> bytes:44+ try:42- return self.decompressor.decompress(data)45+ return self.decompressor.decompress(data)46+ except zlib.error as exc:47+ raise httpcore.exceptions.DecodingError from exc48 49 def flush(self) -> bytes:50+ try:45- return self.decompressor.flush()51+ return self.decompressor.flush()52+ except zlib.error as exc:53+ raise httpcore.exceptions.DecodingError from exc54 55 56 class GZipDecoder(Decoder):57 """5 unmodified lines63 def __init__(self) -> None:64 self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)65 66 def decode(self, data: bytes) -> bytes:67+ try:59- return self.decompressor.decompress(data)68+ return self.decompressor.decompress(data)69+ except zlib.error as exc:70+ raise httpcore.exceptions.DecodingError from exc71 72 def flush(self) -> bytes:73+ try:62- return self.decompressor.flush()74+ return self.decompressor.flush()75+ except zlib.error as exc:76+ raise httpcore.exceptions.DecodingError from exc77 78 79 class BrotliDecoder(Decoder):80 """9 unmodified lines90 ), "The 'brotlipy' library must be installed to use 'BrotliDecoder'"91 self.decompressor = brotli.Decompressor()92 93 def decode(self, data: bytes) -> bytes:94+ try:80- return self.decompressor.decompress(data)95+ return self.decompressor.decompress(data)96+ except brotli.Error as exc:97+ raise httpcore.exceptions.DecodingError from exc98 99 def flush(self) -> bytes:100+ try:83- self.decompressor.finish()84- return b""101+ self.decompressor.finish()102+ return b""103+ except brotli.Error as exc:104+ raise httpcore.exceptions.DecodingError from exc105 106 107 class MultiDecoder(Decoder):108 """89- Handle the case where mutliple encodings have been applied.109+ Handle the case where multiple encodings have been applied.110 """111 112 def __init__(self, children: typing.Sequence[Decoder]) -> None:113 """15 unmodified lines129 return data130 131 132 SUPPORTED_DECODERS = {113- b"identity": IdentityDecoder,114- b"deflate": DeflateDecoder,115- b"gzip": GZipDecoder,116- b"br": BrotliDecoder,133+ "identity": IdentityDecoder,134+ "deflate": DeflateDecoder,135+ "gzip": GZipDecoder,136+ "br": BrotliDecoder,137 }138 139 140 if brotli is None:121- SUPPORTED_DECODERS.pop(b"br") # pragma: nocover141+ SUPPORTED_DECODERS.pop("br") # pragma: nocover142 143 124-ACCEPT_ENCODING = b", ".join(125- [key for key in SUPPORTED_DECODERS.keys() if key != b"identity"]144+ACCEPT_ENCODING = ", ".join(145+ [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]146 )modified:httpcore/exceptions.py+65 added
1+# Timeout exceptions...2+3+4 class Timeout(Exception):5 """6 A base class for all timeouts.7 """10 unmodified lines18 Timeout while reading response data.19 """20 21 22+class WriteTimeout(Timeout):23+ """24+ Timeout while writing request data.25+ """26+27+28 class PoolTimeout(Timeout):29 """30 Timeout while waiting to acquire a connection from the pool.31 """32 33 34+# HTTP exceptions...35+36+37 class ProtocolError(Exception):38 """39 Malformed HTTP.40 """41 42 43+# Redirect exceptions...44+45+46+class RedirectError(Exception):47+ """48+ Base class for HTTP redirect errors.49+ """50+51+52+class TooManyRedirects(RedirectError):53+ """54+ Too many redirects.55+ """56+57+58+class RedirectBodyUnavailable(RedirectError):59+ """60+ Got a redirect response, but the request body was streaming, and is61+ no longer available.62+ """63+64+65+class RedirectLoop(RedirectError):66+ """67+ Infinite redirect loop.68+ """69+70+71+# Response exceptions...72+73+74 class StreamConsumed(Exception):75 """76 Attempted to read or stream response content, but the content has already77 been streamed.78 """79 80 81+class ResponseNotRead(Exception):82+ """83+ Attempted to access response content, without having called `read()`84+ after a streaming response.85+ """86+87+88 class ResponseClosed(Exception):89 """90 Attempted to read or stream response content, but the request has been91 closed without loading the body.92 """93+94+95+class DecodingError(Exception):96+ """97+ Decoding of the response failed.98+ """99+100+101+# Other cases...102+103+104+class InvalidURL(Exception):105+ """106+ URL was missing a hostname, or was not one of HTTP/HTTPS.107+ """deleted:httpcore/http11.py-163 removed
1-import asyncio2-import typing3-4-import h115-6-from .config import DEFAULT_SSL_CONFIG, DEFAULT_TIMEOUT_CONFIG, SSLConfig, TimeoutConfig7-from .datastructures import Client, Origin, Request, Response8-from .exceptions import ConnectTimeout, ReadTimeout9-10-H11Event = typing.Union[11- h11.Request,12- h11.Response,13- h11.InformationalResponse,14- h11.Data,15- h11.EndOfMessage,16- h11.ConnectionClosed,17-]18-19-20-class HTTP11Connection(Client):21- def __init__(22- self,23- origin: typing.Union[str, Origin],24- ssl: SSLConfig = DEFAULT_SSL_CONFIG,25- timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,26- on_release: typing.Callable = None,27- ):28- self.origin = Origin(origin) if isinstance(origin, str) else origin29- self.ssl = ssl30- self.timeout = timeout31- self.on_release = on_release32- self._reader = None33- self._writer = None34- self._h11_state = h11.Connection(our_role=h11.CLIENT)35-36- @property37- def is_closed(self) -> bool:38- return self._h11_state.our_state in (h11.CLOSED, h11.ERROR)39-40- async def send(41- self,42- request: Request,43- *,44- ssl: typing.Optional[SSLConfig] = None,45- timeout: typing.Optional[TimeoutConfig] = None,46- ) -> Response:47- assert request.url.origin == self.origin48-49- if ssl is None:50- ssl = self.ssl51- if timeout is None:52- timeout = self.timeout53-54- # Make the connection55- if self._reader is None:56- await self._connect(ssl, timeout)57-58- # Start sending the request.59- method = request.method.encode()60- target = request.url.target61- headers = request.headers62- event = h11.Request(method=method, target=target, headers=headers)63- await self._send_event(event)64-65- # Send the request body.66- if request.is_streaming:67- async for data in request.stream():68- event = h11.Data(data=data)69- await self._send_event(event)70- elif request.body:71- event = h11.Data(data=request.body)72- await self._send_event(event)73-74- # Finalize sending the request.75- event = h11.EndOfMessage()76- await self._send_event(event)77-78- # Start getting the response.79- event = await self._receive_event(timeout)80- if isinstance(event, h11.InformationalResponse):81- event = await self._receive_event(timeout)82- assert isinstance(event, h11.Response)83- reason = event.reason.decode("latin1")84- status_code = event.status_code85- headers = event.headers86- body = self._body_iter(timeout)87- return Response(88- status_code=status_code,89- reason=reason,90- headers=headers,91- body=body,92- on_close=self._release,93- )94-95- async def _connect(self, ssl: SSLConfig, timeout: TimeoutConfig) -> None:96- hostname = self.origin.hostname97- port = self.origin.port98- ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None99-100- try:101- self._reader, self._writer = await asyncio.wait_for( # type: ignore102- asyncio.open_connection(hostname, port, ssl=ssl_context),103- timeout.connect_timeout,104- )105- except asyncio.TimeoutError:106- raise ConnectTimeout()107-108- async def _body_iter(self, timeout: TimeoutConfig) -> typing.AsyncIterator[bytes]:109- event = await self._receive_event(timeout)110- while isinstance(event, h11.Data):111- yield event.data112- event = await self._receive_event(timeout)113- assert isinstance(event, h11.EndOfMessage)114-115- async def _send_event(self, event: H11Event) -> None:116- assert self._writer is not None117-118- data = self._h11_state.send(event)119- self._writer.write(data)120-121- async def _receive_event(self, timeout: TimeoutConfig) -> H11Event:122- assert self._reader is not None123-124- event = self._h11_state.next_event()125-126- while event is h11.NEED_DATA:127- try:128- data = await asyncio.wait_for(129- self._reader.read(2048), timeout.read_timeout130- )131- except asyncio.TimeoutError:132- raise ReadTimeout()133- self._h11_state.receive_data(data)134- event = self._h11_state.next_event()135-136- return event137-138- async def _release(self) -> None:139- assert self._writer is not None140-141- if (142- self._h11_state.our_state is h11.DONE143- and self._h11_state.their_state is h11.DONE144- ):145- self._h11_state.start_next_cycle()146- else:147- await self.close()148-149- if self.on_release is not None:150- await self.on_release(self)151-152- async def close(self) -> None:153- event = h11.ConnectionClosed()154- try:155- # If we're in h11.MUST_CLOSE then we'll end up in h11.CLOSED.156- self._h11_state.send(event)157- except h11.ProtocolError:158- # If we're in some other state then it's a premature close,159- # and we'll end up in h11.ERROR.160- pass161-162- if self._writer is not None:163- self._writer.close()added:httpcore/interfaces.py+67 added
1+import typing2+from types import TracebackType3+4+from .config import TimeoutConfig5+from .models import URL, ByteOrByteStream, HeaderTypes, Request, Response, URLTypes6+7+OptionalTimeout = typing.Optional[TimeoutConfig]8+9+10+class Adapter:11+ async def request(12+ self,13+ method: str,14+ url: URLTypes,15+ *,16+ headers: HeaderTypes = None,17+ content: ByteOrByteStream = b"",18+ **options: typing.Any,19+ ) -> Response:20+ request = Request(method, url, headers=headers, content=content)21+ self.prepare_request(request)22+ response = await self.send(request, **options)23+ return response24+25+ def prepare_request(self, request: Request) -> None:26+ raise NotImplementedError() # pragma: nocover27+28+ async def send(self, request: Request, **options: typing.Any) -> Response:29+ raise NotImplementedError() # pragma: nocover30+31+ async def close(self) -> None:32+ raise NotImplementedError() # pragma: nocover33+34+ async def __aenter__(self) -> "Adapter":35+ return self36+37+ async def __aexit__(38+ self,39+ exc_type: typing.Type[BaseException] = None,40+ exc_value: BaseException = None,41+ traceback: TracebackType = None,42+ ) -> None:43+ await self.close()44+45+46+class BaseReader:47+ async def read(self, n: int, timeout: OptionalTimeout = None) -> bytes:48+ raise NotImplementedError() # pragma: no cover49+50+51+class BaseWriter:52+ def write_no_block(self, data: bytes) -> None:53+ raise NotImplementedError() # pragma: no cover54+55+ async def write(self, data: bytes, timeout: OptionalTimeout = None) -> None:56+ raise NotImplementedError() # pragma: no cover57+58+ async def close(self) -> None:59+ raise NotImplementedError() # pragma: no cover60+61+62+class BasePoolSemaphore:63+ async def acquire(self) -> None:64+ raise NotImplementedError() # pragma: no cover65+66+ def release(self) -> None:67+ raise NotImplementedError() # pragma: no coveradded:httpcore/models.py+580 added
1+import cgi2+import typing3+4+import chardet5+import rfc39866+7+from .config import SSLConfig, TimeoutConfig8+from .decoders import (9+ ACCEPT_ENCODING,10+ SUPPORTED_DECODERS,11+ Decoder,12+ IdentityDecoder,13+ MultiDecoder,14+)15+from .exceptions import InvalidURL, ResponseClosed, ResponseNotRead, StreamConsumed16+from .status_codes import codes17+from .utils import (18+ get_reason_phrase,19+ is_known_encoding,20+ normalize_header_key,21+ normalize_header_value,22+)23+24+URLTypes = typing.Union["URL", str]25+26+HeaderTypes = typing.Union[27+ "Headers",28+ typing.Dict[typing.AnyStr, typing.AnyStr],29+ typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],30+]31+32+ByteOrByteStream = typing.Union[bytes, typing.AsyncIterator[bytes]]33+34+35+class URL:36+ def __init__(self, url: URLTypes, allow_relative: bool = False) -> None:37+ if isinstance(url, str):38+ self.components = rfc3986.api.uri_reference(url).normalize()39+ elif isinstance(url, rfc3986.uri.URIReference):40+ self.components = url41+ else:42+ self.components = url.components43+44+ if not allow_relative:45+ if not self.scheme:46+ raise InvalidURL("No scheme included in URL.")47+ if self.scheme not in ("http", "https"):48+ raise InvalidURL('URL scheme must be "http" or "https".')49+ if not self.host:50+ raise InvalidURL("No hostname included in URL.")51+52+ @property53+ def scheme(self) -> str:54+ return self.components.scheme or ""55+56+ @property57+ def authority(self) -> str:58+ return self.components.authority or ""59+60+ @property61+ def path(self) -> str:62+ return self.components.path or "/"63+64+ @property65+ def query(self) -> str:66+ return self.components.query or ""67+68+ @property69+ def fragment(self) -> str:70+ return self.components.fragment or ""71+72+ @property73+ def host(self) -> str:74+ return self.components.host or ""75+76+ @property77+ def port(self) -> int:78+ port = self.components.port79+ if port is None:80+ return {"https": 443, "http": 80}[self.scheme]81+ return port82+83+ @property84+ def full_path(self) -> str:85+ path = self.path or "/"86+ query = self.query87+ if query:88+ return path + "?" + query89+ return path90+91+ @property92+ def is_secure(self) -> bool:93+ return self.components.scheme == "https"94+95+ @property96+ def is_absolute(self) -> bool:97+ return self.components.is_absolute()98+99+ @property100+ def origin(self) -> "Origin":101+ return Origin(self)102+103+ def copy_with(self, **kwargs: typing.Any) -> "URL":104+ return URL(self.components.copy_with(**kwargs))105+106+ def resolve_with(self, base_url: URLTypes) -> "URL":107+ if isinstance(base_url, URL):108+ base_url = base_url.components109+ return URL(self.components.resolve_with(base_url))110+111+ def __hash__(self) -> int:112+ return hash(str(self))113+114+ def __eq__(self, other: typing.Any) -> bool:115+ return isinstance(other, URL) and str(self) == str(other)116+117+ def __str__(self) -> str:118+ return self.components.unsplit()119+120+ def __repr__(self) -> str:121+ class_name = self.__class__.__name__122+ url_str = str(self)123+ return f"{class_name}({url_str!r})"124+125+126+class Origin:127+ def __init__(self, url: URLTypes) -> None:128+ if not isinstance(url, URL):129+ url = URL(url)130+ self.is_ssl = url.scheme == "https"131+ self.host = url.host132+ self.port = url.port133+134+ def __eq__(self, other: typing.Any) -> bool:135+ return (136+ isinstance(other, self.__class__)137+ and self.is_ssl == other.is_ssl138+ and self.host == other.host139+ and self.port == other.port140+ )141+142+ def __hash__(self) -> int:143+ return hash((self.is_ssl, self.host, self.port))144+145+146+class Headers(typing.MutableMapping[str, str]):147+ """148+ A case-insensitive multidict.149+ """150+151+ def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:152+ if headers is None:153+ self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]154+ elif isinstance(headers, Headers):155+ self._list = list(headers.raw)156+ elif isinstance(headers, dict):157+ self._list = [158+ (normalize_header_key(k, encoding), normalize_header_value(v, encoding))159+ for k, v in headers.items()160+ ]161+ else:162+ self._list = [163+ (normalize_header_key(k, encoding), normalize_header_value(v, encoding))164+ for k, v in headers165+ ]166+ self._encoding = encoding167+168+ @property169+ def encoding(self) -> str:170+ """171+ Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be172+ seen in the wild.173+ """174+ if self._encoding is None:175+ for encoding in ["ascii", "utf-8"]:176+ for key, value in self.raw:177+ try:178+ key.decode(encoding)179+ value.decode(encoding)180+ except UnicodeDecodeError:181+ break182+ else:183+ # The else block runs if 'break' did not occur, meaning184+ # all values fitted the encoding.185+ self._encoding = encoding186+ break187+ else:188+ # The ISO-8859-1 encoding covers all 256 code points in a byte,189+ # so will never raise decode errors.190+ self._encoding = "iso-8859-1"191+ return self._encoding192+193+ @encoding.setter194+ def encoding(self, value: str) -> None:195+ self._encoding = value196+197+ @property198+ def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:199+ """200+ Returns a list of the raw header items, as byte pairs.201+ May be mutated in-place.202+ """203+ return self._list204+205+ def keys(self) -> typing.List[str]: # type: ignore206+ return [key.decode(self.encoding) for key, value in self._list]207+208+ def values(self) -> typing.List[str]: # type: ignore209+ return [value.decode(self.encoding) for key, value in self._list]210+211+ def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore212+ return [213+ (key.decode(self.encoding), value.decode(self.encoding))214+ for key, value in self._list215+ ]216+217+ def get(self, key: str, default: typing.Any = None) -> typing.Any:218+ try:219+ return self[key]220+ except KeyError:221+ return default222+223+ def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:224+ """225+ Return multiple header values.226+ """227+ get_header_key = key.lower().encode(self.encoding)228+229+ values = [230+ item_value.decode(self.encoding)231+ for item_key, item_value in self._list232+ if item_key == get_header_key233+ ]234+235+ if not split_commas:236+ return values237+238+ split_values = []239+ for value in values:240+ split_values.extend([item.strip() for item in value.split(",")])241+ return split_values242+243+ def __getitem__(self, key: str) -> str:244+ """245+ Return a single header value.246+247+ If there are multiple headers with the same key, then we concatenate248+ them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2249+ """250+ normalized_key = key.lower().encode(self.encoding)251+252+ items = []253+ for header_key, header_value in self._list:254+ if header_key == normalized_key:255+ items.append(header_value.decode(self.encoding))256+257+ if items:258+ return ", ".join(items)259+260+ raise KeyError(key)261+262+ def __setitem__(self, key: str, value: str) -> None:263+ """264+ Set the header `key` to `value`, removing any duplicate entries.265+ Retains insertion order.266+ """267+ set_key = key.lower().encode(self.encoding)268+ set_value = value.encode(self.encoding)269+270+ found_indexes = []271+ for idx, (item_key, item_value) in enumerate(self._list):272+ if item_key == set_key:273+ found_indexes.append(idx)274+275+ for idx in reversed(found_indexes[1:]):276+ del self._list[idx]277+278+ if found_indexes:279+ idx = found_indexes[0]280+ self._list[idx] = (set_key, set_value)281+ else:282+ self._list.append((set_key, set_value))283+284+ def __delitem__(self, key: str) -> None:285+ """286+ Remove the header `key`.287+ """288+ del_key = key.lower().encode(self.encoding)289+290+ pop_indexes = []291+ for idx, (item_key, item_value) in enumerate(self._list):292+ if item_key == del_key:293+ pop_indexes.append(idx)294+295+ for idx in reversed(pop_indexes):296+ del self._list[idx]297+298+ def __contains__(self, key: typing.Any) -> bool:299+ get_header_key = key.lower().encode(self.encoding)300+ for header_key, header_value in self._list:301+ if header_key == get_header_key:302+ return True303+ return False304+305+ def __iter__(self) -> typing.Iterator[typing.Any]:306+ return iter(self.keys())307+308+ def __len__(self) -> int:309+ return len(self._list)310+311+ def __eq__(self, other: typing.Any) -> bool:312+ if not isinstance(other, Headers):313+ return False314+ return sorted(self._list) == sorted(other._list)315+316+ def __repr__(self) -> str:317+ class_name = self.__class__.__name__318+319+ encoding_str = ""320+ if self.encoding != "ascii":321+ encoding_str = f", encoding={self.encoding!r}"322+323+ as_dict = dict(self.items())324+ if len(as_dict) == len(self):325+ return f"{class_name}({as_dict!r}{encoding_str})"326+ as_list = self.items()327+ return f"{class_name}({as_list!r}{encoding_str})"328+329+330+class Request:331+ def __init__(332+ self,333+ method: str,334+ url: typing.Union[str, URL],335+ *,336+ headers: HeaderTypes = None,337+ content: ByteOrByteStream = b"",338+ ):339+ self.method = method.upper()340+ self.url = URL(url) if isinstance(url, str) else url341+ if isinstance(content, bytes):342+ self.is_streaming = False343+ self.content = content344+ else:345+ self.is_streaming = True346+ self.content_aiter = content347+ self.headers = Headers(headers)348+349+ async def read(self) -> bytes:350+ """351+ Read and return the response content.352+ """353+ if not hasattr(self, "content"):354+ content = b""355+ async for part in self.stream():356+ content += part357+ self.content = content358+ return self.content359+360+ async def stream(self) -> typing.AsyncIterator[bytes]:361+ if self.is_streaming:362+ async for part in self.content_aiter:363+ yield part364+ elif self.content:365+ yield self.content366+367+ def prepare(self) -> None:368+ """369+ Adds in any default headers. When using the `Client`, this will370+ end up being called into by the `prepare_request()` stage.371+372+ You can omit this behavior by calling `Client.send()` with an373+ explicitly built `Request` instance.374+ """375+ auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]376+377+ has_host = "host" in self.headers378+ has_content_length = (379+ "content-length" in self.headers or "transfer-encoding" in self.headers380+ )381+ has_accept_encoding = "accept-encoding" in self.headers382+383+ if not has_host and self.url.authority:384+ auto_headers.append((b"host", self.url.authority.encode("ascii")))385+ if not has_content_length:386+ if self.is_streaming:387+ auto_headers.append((b"transfer-encoding", b"chunked"))388+ elif self.content:389+ content_length = str(len(self.content)).encode()390+ auto_headers.append((b"content-length", content_length))391+ if not has_accept_encoding:392+ auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))393+394+ for item in reversed(auto_headers):395+ self.headers.raw.insert(0, item)396+397+398+class Response:399+ def __init__(400+ self,401+ status_code: int,402+ *,403+ reason_phrase: str = None,404+ protocol: str = None,405+ headers: HeaderTypes = None,406+ content: ByteOrByteStream = b"",407+ on_close: typing.Callable = None,408+ request: Request = None,409+ history: typing.List["Response"] = None,410+ ):411+ self.status_code = status_code412+ self.reason_phrase = reason_phrase or get_reason_phrase(status_code)413+ self.protocol = protocol414+ self.headers = Headers(headers)415+416+ if isinstance(content, bytes):417+ self.is_closed = True418+ self.is_stream_consumed = True419+ self._raw_content = content420+ else:421+ self.is_closed = False422+ self.is_stream_consumed = False423+ self._raw_stream = content424+425+ self.on_close = on_close426+ self.request = request427+ self.history = [] if history is None else list(history)428+ self.next = None # typing.Optional[typing.Callable]429+430+ @property431+ def url(self) -> typing.Optional[URL]:432+ """433+ Returns the URL for which the request was made.434+435+ Requires that `request` was provided when instantiating the response.436+ """437+ return None if self.request is None else self.request.url438+439+ @property440+ def content(self) -> bytes:441+ if not hasattr(self, "_content"):442+ if hasattr(self, "_raw_content"):443+ content = self.decoder.decode(self._raw_content)444+ content += self.decoder.flush()445+ self._content = content446+ else:447+ raise ResponseNotRead()448+ return self._content449+450+ @property451+ def text(self) -> str:452+ if not hasattr(self, "_text"):453+ content = self.content454+ if not content:455+ self._text = ""456+ else:457+ encoding = self.encoding458+ self._text = content.decode(encoding, errors="replace")459+ return self._text460+461+ @property462+ def encoding(self) -> str:463+ if not hasattr(self, "_encoding"):464+ encoding = self.charset_encoding465+ if encoding is None or not is_known_encoding(encoding):466+ encoding = self.apparent_encoding467+ if encoding is None or not is_known_encoding(encoding):468+ encoding = "utf-8"469+ self._encoding = encoding470+ return self._encoding471+472+ @encoding.setter473+ def encoding(self, value: str) -> None:474+ self._encoding = value475+476+ @property477+ def charset_encoding(self) -> typing.Optional[str]:478+ """479+ Return the encoding, as specified by the Content-Type header.480+ """481+ content_type = self.headers.get("Content-Type")482+ if content_type is None:483+ return None484+485+ parsed = cgi.parse_header(content_type)[-1]486+ return parsed.get("charset")487+488+ @property489+ def apparent_encoding(self) -> typing.Optional[str]:490+ """491+ Return the encoding, as it appears to autodetection.492+ """493+ return chardet.detect(self.content)["encoding"]494+495+ @property496+ def decoder(self) -> Decoder:497+ """498+ Returns a decoder instance which can be used to decode the raw byte499+ content, depending on the Content-Encoding used in the response.500+ """501+ if not hasattr(self, "_decoder"):502+ decoders = [] # type: typing.List[Decoder]503+ values = self.headers.getlist("content-encoding", split_commas=True)504+ for value in values:505+ value = value.strip().lower()506+ decoder_cls = SUPPORTED_DECODERS[value]507+ decoders.append(decoder_cls())508+509+ if len(decoders) == 1:510+ self._decoder = decoders[0]511+ elif len(decoders) > 1:512+ self._decoder = MultiDecoder(decoders)513+ else:514+ self._decoder = IdentityDecoder()515+516+ return self._decoder517+518+ async def read(self) -> bytes:519+ """520+ Read and return the response content.521+ """522+ if not hasattr(self, "_content"):523+ content = b""524+ async for part in self.stream():525+ content += part526+ self._content = content527+ return self._content528+529+ async def stream(self) -> typing.AsyncIterator[bytes]:530+ """531+ A byte-iterator over the decoded response content.532+ This allows us to handle gzip, deflate, and brotli encoded responses.533+ """534+ if hasattr(self, "_content"):535+ yield self._content536+ else:537+ async for chunk in self.raw():538+ yield self.decoder.decode(chunk)539+ yield self.decoder.flush()540+541+ async def raw(self) -> typing.AsyncIterator[bytes]:542+ """543+ A byte-iterator over the raw response content.544+ """545+ if hasattr(self, "_raw_content"):546+ yield self._raw_content547+ else:548+ if self.is_stream_consumed:549+ raise StreamConsumed()550+ if self.is_closed:551+ raise ResponseClosed()552+553+ self.is_stream_consumed = True554+ async for part in self._raw_stream:555+ yield part556+ await self.close()557+558+ async def close(self) -> None:559+ """560+ Close the response and release the connection.561+ Automatically called if the response body is read to completion.562+ """563+ if not self.is_closed:564+ self.is_closed = True565+ if self.on_close is not None:566+ await self.on_close()567+568+ @property569+ def is_redirect(self) -> bool:570+ return (571+ self.status_code572+ in (573+ codes.moved_permanently,574+ codes.found,575+ codes.see_other,576+ codes.temporary_redirect,577+ codes.permanent_redirect,578+ )579+ and "location" in self.headers580+ )added:httpcore/status_codes.py+61 added
1+import enum2+3+codes = enum.IntEnum(4+ "StatusCode",5+ [6+ ("continue", 100),7+ ("switching_protocols", 101),8+ ("processing", 102),9+ ("ok", 200),10+ ("created", 201),11+ ("accepted", 202),12+ ("non_authoritative_information", 203),13+ ("no_content", 204),14+ ("reset_content", 205),15+ ("partial_content", 206),16+ ("multi_status", 207),17+ ("already_reported", 208),18+ ("im_used", 226),19+ ("multiple_choices", 300),20+ ("moved_permanently", 301),21+ ("found", 302),22+ ("see_other", 303),23+ ("not_modified", 304),24+ ("use_proxy", 305),25+ ("temporary_redirect", 307),26+ ("permanent_redirect", 308),27+ ("bad_request", 400),28+ ("unauthorized", 401),29+ ("payment_required", 402),30+ ("forbidden", 403),31+ ("not_found", 404),32+ ("method_not_allowed", 405),33+ ("not_acceptable", 406),34+ ("proxy_authentication_required", 407),35+ ("request_timeout", 408),36+ ("conflict", 409),37+ ("gone", 410),38+ ("length_required", 411),39+ ("precondition_failed", 412),40+ ("request_entity_too_large", 413),41+ ("request_uri_too_long", 414),42+ ("unsupported_media_type", 415),43+ ("requested_range_not_satisfiable", 416),44+ ("expectation_failed", 417),45+ ("unprocessable_entity", 422),46+ ("locked", 423),47+ ("failed_dependency", 424),48+ ("precondition_required", 428),49+ ("too_many_requests", 429),50+ ("request_header_fields_too_large", 431),51+ ("unavailable_for_legal_reasons", 451),52+ ("internal_server_error", 500),53+ ("not_implemented", 501),54+ ("bad_gateway", 502),55+ ("service_unavailable", 503),56+ ("gateway_timeout", 504),57+ ("http_version_not_supported", 505),58+ ("insufficient_storage", 507),59+ ("network_authentication_required", 511),60+ ],61+)added:httpcore/streams.py+133 added
1+"""2+The `Reader` and `Writer` classes here provide a lightweight layer over3+`asyncio.StreamReader` and `asyncio.StreamWriter`.4+5+Similarly `PoolSemaphore` is a lightweight layer over `BoundedSemaphore`.6+7+These classes help encapsulate the timeout logic, make it easier to unit-test8+protocols, and help keep the rest of the package more `async`/`await`9+based, and less strictly `asyncio`-specific.10+"""11+import asyncio12+import enum13+import ssl14+import typing15+16+from .config import DEFAULT_TIMEOUT_CONFIG, PoolLimits, TimeoutConfig17+from .exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout18+from .interfaces import BasePoolSemaphore, BaseReader, BaseWriter19+20+OptionalTimeout = typing.Optional[TimeoutConfig]21+22+23+class Protocol(enum.Enum):24+ HTTP_11 = 125+ HTTP_2 = 226+27+28+class Reader(BaseReader):29+ def __init__(30+ self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig31+ ) -> None:32+ self.stream_reader = stream_reader33+ self.timeout = timeout34+35+ async def read(self, n: int, timeout: OptionalTimeout = None) -> bytes:36+ if timeout is None:37+ timeout = self.timeout38+39+ try:40+ data = await asyncio.wait_for(41+ self.stream_reader.read(n), timeout.read_timeout42+ )43+ except asyncio.TimeoutError:44+ raise ReadTimeout()45+46+ return data47+48+49+class Writer(BaseWriter):50+ def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):51+ self.stream_writer = stream_writer52+ self.timeout = timeout53+54+ def write_no_block(self, data: bytes) -> None:55+ self.stream_writer.write(data)56+57+ async def write(self, data: bytes, timeout: OptionalTimeout = None) -> None:58+ if not data:59+ return60+61+ if timeout is None:62+ timeout = self.timeout63+64+ self.stream_writer.write(data)65+ try:66+ data = await asyncio.wait_for( # type: ignore67+ self.stream_writer.drain(), timeout.write_timeout68+ )69+ except asyncio.TimeoutError:70+ raise WriteTimeout()71+72+ async def close(self) -> None:73+ self.stream_writer.close()74+75+76+class PoolSemaphore(BasePoolSemaphore):77+ def __init__(self, limits: PoolLimits):78+ self.limits = limits79+80+ @property81+ def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:82+ if not hasattr(self, "_semaphore"):83+ max_connections = self.limits.hard_limit84+ if max_connections is None:85+ self._semaphore = None86+ else:87+ self._semaphore = asyncio.BoundedSemaphore(value=max_connections)88+ return self._semaphore89+90+ async def acquire(self) -> None:91+ if self.semaphore is None:92+ return93+94+ timeout = self.limits.pool_timeout95+ try:96+ await asyncio.wait_for(self.semaphore.acquire(), timeout)97+ except asyncio.TimeoutError:98+ raise PoolTimeout()99+100+ def release(self) -> None:101+ if self.semaphore is None:102+ return103+104+ self.semaphore.release()105+106+107+async def connect(108+ hostname: str,109+ port: int,110+ ssl_context: typing.Optional[ssl.SSLContext] = None,111+ timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,112+) -> typing.Tuple[Reader, Writer, Protocol]:113+ try:114+ stream_reader, stream_writer = await asyncio.wait_for( # type: ignore115+ asyncio.open_connection(hostname, port, ssl=ssl_context),116+ timeout.connect_timeout,117+ )118+ except asyncio.TimeoutError:119+ raise ConnectTimeout()120+121+ ssl_object = stream_writer.get_extra_info("ssl_object")122+ if ssl_object is None:123+ ident = "http/1.1"124+ else:125+ ident = ssl_object.selected_alpn_protocol()126+ if ident is None:127+ ident = ssl_object.selected_npn_protocol()128+129+ reader = Reader(stream_reader=stream_reader, timeout=timeout)130+ writer = Writer(stream_writer=stream_writer, timeout=timeout)131+ protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11132+133+ return (reader, writer, protocol)modified:httpcore/sync.py+13 added-22 removed
1 unmodified line2 import typing3 from types import TracebackType4 5 from .config import SSLConfig, TimeoutConfig6-from .connectionpool import ConnectionPool7-from .datastructures import URL, Client, Response6+from .dispatch.connection_pool import ConnectionPool7+from .interfaces import Adapter8+from .models import URL, Headers, Response9 10 11 class SyncResponse:12 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):4 unmodified lines17 def status_code(self) -> int:18 return self._response.status_code19 20 @property20- def reason(self) -> str:21- return self._response.reason21+ def reason_phrase(self) -> str:22+ return self._response.reason_phrase23 24 @property24- def headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:25+ def headers(self) -> Headers:26 return self._response.headers27 28 @property28- def body(self) -> bytes:29- return self._response.body29+ def content(self) -> bytes:30+ return self._response.content31 32 def read(self) -> bytes:33 return self._loop.run_until_complete(self._response.read())34 17 unmodified lines52 return self._loop.run_until_complete(self._response.close())53 54 55 class SyncClient:55- def __init__(self, client: Client):56- self._client = client56+ def __init__(self, adapter: Adapter):57+ self._client = adapter58 self._loop = asyncio.new_event_loop()59 60 def request(61 self,62 method: str,63 url: typing.Union[str, URL],64 *,64- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),65+ headers: typing.List[typing.Tuple[bytes, bytes]] = [],66 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",66- ssl: typing.Optional[SSLConfig] = None,67- timeout: typing.Optional[TimeoutConfig] = None,68- stream: bool = False,67+ **options: typing.Any68 ) -> SyncResponse:69 response = self._loop.run_until_complete(71- self._client.request(72- method,73- url,74- headers=headers,75- body=body,76- ssl=ssl,77- timeout=timeout,78- stream=stream,79- )70+ self._client.request(method, url, headers=headers, body=body, **options)71 )72 return SyncResponse(response, self._loop)73 74 def close(self) -> None:17 unmodified linesadded:httpcore/utils.py+39 added
1+import codecs2+import http3+import typing4+5+6+def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:7+ """8+ Coerce str/bytes into a strictly byte-wise HTTP header key.9+ """10+ if isinstance(value, bytes):11+ return value.lower()12+ return value.encode(encoding or "ascii").lower()13+14+15+def normalize_header_value(value: typing.AnyStr, encoding: str = None) -> bytes:16+ """17+ Coerce str/bytes into a strictly byte-wise HTTP header value.18+ """19+ if isinstance(value, bytes):20+ return value21+ return value.encode(encoding or "ascii")22+23+24+def get_reason_phrase(status_code: int) -> str:25+ """26+ Return an HTTP reason phrase, eg. "OK" for 200, or "Not Found" for 404.27+ """28+ try:29+ return http.HTTPStatus(status_code).phrase30+ except ValueError as exc:31+ return ""32+33+34+def is_known_encoding(encoding: str) -> bool:35+ try:36+ codecs.lookup(encoding)37+ except LookupError:38+ return False39+ return Trueadded:tests/adapters/test_redirects.py+241 added
1+import json2+from urllib.parse import parse_qs3+4+import pytest5+6+from httpcore import (7+ URL,8+ Adapter,9+ RedirectAdapter,10+ RedirectBodyUnavailable,11+ RedirectLoop,12+ Request,13+ Response,14+ TooManyRedirects,15+ codes,16+)17+18+19+class MockDispatch(Adapter):20+ def prepare_request(self, request: Request) -> None:21+ pass22+23+ async def send(self, request: Request, **options) -> Response:24+ if request.url.path == "/redirect_301":25+ status_code = codes.moved_permanently26+ headers = {"location": "https://example.org/"}27+ return Response(status_code, headers=headers, request=request)28+29+ elif request.url.path == "/redirect_302":30+ status_code = codes.found31+ headers = {"location": "https://example.org/"}32+ return Response(status_code, headers=headers, request=request)33+34+ elif request.url.path == "/redirect_303":35+ status_code = codes.see_other36+ headers = {"location": "https://example.org/"}37+ return Response(status_code, headers=headers, request=request)38+39+ elif request.url.path == "/relative_redirect":40+ headers = {"location": "/"}41+ return Response(codes.see_other, headers=headers, request=request)42+43+ elif request.url.path == "/no_scheme_redirect":44+ headers = {"location": "//example.org/"}45+ return Response(codes.see_other, headers=headers, request=request)46+47+ elif request.url.path == "/multiple_redirects":48+ params = parse_qs(request.url.query)49+ count = int(params.get("count", "0")[0])50+ redirect_count = count - 151+ code = codes.see_other if count else codes.ok52+ location = "/multiple_redirects"53+ if redirect_count:54+ location += "?count=" + str(redirect_count)55+ headers = {"location": location} if count else {}56+ return Response(code, headers=headers, request=request)57+58+ if request.url.path == "/redirect_loop":59+ headers = {"location": "/redirect_loop"}60+ return Response(codes.see_other, headers=headers, request=request)61+62+ elif request.url.path == "/cross_domain":63+ headers = {"location": "https://example.org/cross_domain_target"}64+ return Response(codes.see_other, headers=headers, request=request)65+66+ elif request.url.path == "/cross_domain_target":67+ headers = dict(request.headers.items())68+ content = json.dumps({"headers": headers}).encode()69+ return Response(codes.ok, content=content, request=request)70+71+ elif request.url.path == "/redirect_body":72+ await request.read()73+ headers = {"location": "/redirect_body_target"}74+ return Response(codes.permanent_redirect, headers=headers, request=request)75+76+ elif request.url.path == "/redirect_body_target":77+ content = await request.read()78+ body = json.dumps({"body": content.decode()}).encode()79+ return Response(codes.ok, content=body, request=request)80+81+ return Response(codes.ok, content=b"Hello, world!", request=request)82+83+84+@pytest.mark.asyncio85+async def test_redirect_301():86+ client = RedirectAdapter(MockDispatch())87+ response = await client.request("POST", "https://example.org/redirect_301")88+ assert response.status_code == codes.ok89+ assert response.url == URL("https://example.org/")90+ assert len(response.history) == 191+92+93+@pytest.mark.asyncio94+async def test_redirect_302():95+ client = RedirectAdapter(MockDispatch())96+ response = await client.request("POST", "https://example.org/redirect_302")97+ assert response.status_code == codes.ok98+ assert response.url == URL("https://example.org/")99+ assert len(response.history) == 1100+101+102+@pytest.mark.asyncio103+async def test_redirect_303():104+ client = RedirectAdapter(MockDispatch())105+ response = await client.request("GET", "https://example.org/redirect_303")106+ assert response.status_code == codes.ok107+ assert response.url == URL("https://example.org/")108+ assert len(response.history) == 1109+110+111+@pytest.mark.asyncio112+async def test_disallow_redirects():113+ client = RedirectAdapter(MockDispatch())114+ response = await client.request(115+ "POST", "https://example.org/redirect_303", allow_redirects=False116+ )117+ assert response.status_code == codes.see_other118+ assert response.url == URL("https://example.org/redirect_303")119+ assert len(response.history) == 0120+121+ response = await response.next()122+ assert response.status_code == codes.ok123+ assert response.url == URL("https://example.org/")124+ assert len(response.history) == 1125+126+127+@pytest.mark.asyncio128+async def test_relative_redirect():129+ client = RedirectAdapter(MockDispatch())130+ response = await client.request("GET", "https://example.org/relative_redirect")131+ assert response.status_code == codes.ok132+ assert response.url == URL("https://example.org/")133+ assert len(response.history) == 1134+135+136+@pytest.mark.asyncio137+async def test_no_scheme_redirect():138+ client = RedirectAdapter(MockDispatch())139+ response = await client.request("GET", "https://example.org/no_scheme_redirect")140+ assert response.status_code == codes.ok141+ assert response.url == URL("https://example.org/")142+ assert len(response.history) == 1143+144+145+@pytest.mark.asyncio146+async def test_fragment_redirect():147+ client = RedirectAdapter(MockDispatch())148+ url = "https://example.org/relative_redirect#fragment"149+ response = await client.request("GET", url)150+ assert response.status_code == codes.ok151+ assert response.url == URL("https://example.org/#fragment")152+ assert len(response.history) == 1153+154+155+@pytest.mark.asyncio156+async def test_multiple_redirects():157+ client = RedirectAdapter(MockDispatch())158+ url = "https://example.org/multiple_redirects?count=20"159+ response = await client.request("GET", url)160+ assert response.status_code == codes.ok161+ assert response.url == URL("https://example.org/multiple_redirects")162+ assert len(response.history) == 20163+164+165+@pytest.mark.asyncio166+async def test_too_many_redirects():167+ client = RedirectAdapter(MockDispatch())168+ with pytest.raises(TooManyRedirects):169+ await client.request("GET", "https://example.org/multiple_redirects?count=21")170+171+172+@pytest.mark.asyncio173+async def test_too_many_redirects_calling_next():174+ client = RedirectAdapter(MockDispatch())175+ url = "https://example.org/multiple_redirects?count=21"176+ response = await client.request("GET", url, allow_redirects=False)177+ with pytest.raises(TooManyRedirects):178+ while response.is_redirect:179+ response = await response.next()180+181+182+@pytest.mark.asyncio183+async def test_redirect_loop():184+ client = RedirectAdapter(MockDispatch())185+ with pytest.raises(RedirectLoop):186+ await client.request("GET", "https://example.org/redirect_loop")187+188+189+@pytest.mark.asyncio190+async def test_redirect_loop_calling_next():191+ client = RedirectAdapter(MockDispatch())192+ url = "https://example.org/redirect_loop"193+ response = await client.request("GET", url, allow_redirects=False)194+ with pytest.raises(RedirectLoop):195+ while response.is_redirect:196+ response = await response.next()197+198+199+@pytest.mark.asyncio200+async def test_cross_domain_redirect():201+ client = RedirectAdapter(MockDispatch())202+ url = "https://example.com/cross_domain"203+ headers = {"Authorization": "abc"}204+ response = await client.request("GET", url, headers=headers)205+ data = json.loads(response.content.decode())206+ assert response.url == URL("https://example.org/cross_domain_target")207+ assert data == {"headers": {}}208+209+210+@pytest.mark.asyncio211+async def test_same_domain_redirect():212+ client = RedirectAdapter(MockDispatch())213+ url = "https://example.org/cross_domain"214+ headers = {"Authorization": "abc"}215+ response = await client.request("GET", url, headers=headers)216+ data = json.loads(response.content.decode())217+ assert response.url == URL("https://example.org/cross_domain_target")218+ assert data == {"headers": {"authorization": "abc"}}219+220+221+@pytest.mark.asyncio222+async def test_body_redirect():223+ client = RedirectAdapter(MockDispatch())224+ url = "https://example.org/redirect_body"225+ content = b"Example request body"226+ response = await client.request("POST", url, content=content)227+ data = json.loads(response.content.decode())228+ assert response.url == URL("https://example.org/redirect_body_target")229+ assert data == {"body": "Example request body"}230+231+232+@pytest.mark.asyncio233+async def test_cannot_redirect_streaming_body():234+ client = RedirectAdapter(MockDispatch())235+ url = "https://example.org/redirect_body"236+237+ async def streaming_body():238+ yield b"Example request body"239+240+ with pytest.raises(RedirectBodyUnavailable):241+ await client.request("POST", url, content=streaming_body())added:tests/dispatch/test_connection_pools.py+126 added
1+import pytest2+3+import httpcore4+5+6+@pytest.mark.asyncio7+async def test_keepalive_connections(server):8+ """9+ Connections should default to staying in a keep-alive state.10+ """11+ async with httpcore.ConnectionPool() as http:12+ response = await http.request("GET", "http://127.0.0.1:8000/")13+ assert len(http.active_connections) == 014+ assert len(http.keepalive_connections) == 115+16+ response = await http.request("GET", "http://127.0.0.1:8000/")17+ assert len(http.active_connections) == 018+ assert len(http.keepalive_connections) == 119+20+21+@pytest.mark.asyncio22+async def test_differing_connection_keys(server):23+ """24+ Connnections to differing connection keys should result in multiple connections.25+ """26+ async with httpcore.ConnectionPool() as http:27+ response = await http.request("GET", "http://127.0.0.1:8000/")28+ assert len(http.active_connections) == 029+ assert len(http.keepalive_connections) == 130+31+ response = await http.request("GET", "http://localhost:8000/")32+ assert len(http.active_connections) == 033+ assert len(http.keepalive_connections) == 234+35+36+@pytest.mark.asyncio37+async def test_soft_limit(server):38+ """39+ The soft_limit config should limit the maximum number of keep-alive connections.40+ """41+ limits = httpcore.PoolLimits(soft_limit=1)42+43+ async with httpcore.ConnectionPool(limits=limits) as http:44+ response = await http.request("GET", "http://127.0.0.1:8000/")45+ assert len(http.active_connections) == 046+ assert len(http.keepalive_connections) == 147+48+ response = await http.request("GET", "http://localhost:8000/")49+ assert len(http.active_connections) == 050+ assert len(http.keepalive_connections) == 151+52+53+@pytest.mark.asyncio54+async def test_streaming_response_holds_connection(server):55+ """56+ A streaming request should hold the connection open until the response is read.57+ """58+ async with httpcore.ConnectionPool() as http:59+ response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)60+ assert len(http.active_connections) == 161+ assert len(http.keepalive_connections) == 062+63+ await response.read()64+65+ assert len(http.active_connections) == 066+ assert len(http.keepalive_connections) == 167+68+69+@pytest.mark.asyncio70+async def test_multiple_concurrent_connections(server):71+ """72+ Multiple conncurrent requests should open multiple conncurrent connections.73+ """74+ async with httpcore.ConnectionPool() as http:75+ response_a = await http.request("GET", "http://127.0.0.1:8000/", stream=True)76+ assert len(http.active_connections) == 177+ assert len(http.keepalive_connections) == 078+79+ response_b = await http.request("GET", "http://127.0.0.1:8000/", stream=True)80+ assert len(http.active_connections) == 281+ assert len(http.keepalive_connections) == 082+83+ await response_b.read()84+ assert len(http.active_connections) == 185+ assert len(http.keepalive_connections) == 186+87+ await response_a.read()88+ assert len(http.active_connections) == 089+ assert len(http.keepalive_connections) == 290+91+92+@pytest.mark.asyncio93+async def test_close_connections(server):94+ """95+ Using a `Connection: close` header should close the connection.96+ """97+ headers = [(b"connection", b"close")]98+ async with httpcore.ConnectionPool() as http:99+ response = await http.request("GET", "http://127.0.0.1:8000/", headers=headers)100+ assert len(http.active_connections) == 0101+ assert len(http.keepalive_connections) == 0102+103+104+@pytest.mark.asyncio105+async def test_standard_response_close(server):106+ """107+ A standard close should keep the connection open.108+ """109+ async with httpcore.ConnectionPool() as http:110+ response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)111+ await response.read()112+ await response.close()113+ assert len(http.active_connections) == 0114+ assert len(http.keepalive_connections) == 1115+116+117+@pytest.mark.asyncio118+async def test_premature_response_close(server):119+ """120+ A premature close should close the connection.121+ """122+ async with httpcore.ConnectionPool() as http:123+ response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)124+ await response.close()125+ assert len(http.active_connections) == 0126+ assert len(http.keepalive_connections) == 0added:tests/dispatch/test_connections.py+20 added
1+import pytest2+3+import httpcore4+5+6+@pytest.mark.asyncio7+async def test_get(server):8+ http = httpcore.HTTPConnection(origin="http://127.0.0.1:8000/")9+ response = await http.request("GET", "http://127.0.0.1:8000/")10+ assert response.status_code == 20011+ assert response.content == b"Hello, world!"12+13+14+@pytest.mark.asyncio15+async def test_post(server):16+ http = httpcore.HTTPConnection(origin="http://127.0.0.1:8000/")17+ response = await http.request(18+ "POST", "http://127.0.0.1:8000/", body=b"Hello, world!"19+ )20+ assert response.status_code == 200added:tests/dispatch/test_http2.py+116 added
1+import json2+3+import h2.config4+import h2.connection5+import h2.events6+import pytest7+8+import httpcore9+10+11+class MockServer(httpcore.BaseReader, httpcore.BaseWriter):12+ """13+ This class exposes Reader and Writer style interfaces14+ """15+16+ def __init__(self):17+ config = h2.config.H2Configuration(client_side=False)18+ self.conn = h2.connection.H2Connection(config=config)19+ self.buffer = b""20+ self.requests = {}21+22+ # BaseReader interface23+24+ async def read(self, n, timeout) -> bytes:25+ send, self.buffer = self.buffer[:n], self.buffer[n:]26+ return send27+28+ # BaseWriter interface29+30+ def write_no_block(self, data: bytes) -> None:31+ events = self.conn.receive_data(data)32+ self.buffer += self.conn.data_to_send()33+ for event in events:34+ if isinstance(event, h2.events.RequestReceived):35+ self.request_received(event.headers, event.stream_id)36+ elif isinstance(event, h2.events.DataReceived):37+ self.receive_data(event.data, event.stream_id)38+ elif isinstance(event, h2.events.StreamEnded):39+ self.stream_complete(event.stream_id)40+41+ async def write(self, data: bytes, timeout) -> None:42+ self.write_no_block(data)43+44+ async def close(self) -> None:45+ pass46+47+ # Server implementation48+49+ def request_received(self, headers, stream_id):50+ if stream_id not in self.requests:51+ self.requests[stream_id] = []52+ self.requests[stream_id].append({"headers": headers, "data": b""})53+54+ def receive_data(self, data, stream_id):55+ self.requests[stream_id][-1]["data"] += data56+57+ def stream_complete(self, stream_id):58+ request = self.requests[stream_id].pop(0)59+ if not self.requests[stream_id]:60+ del self.requests[stream_id]61+62+ request_headers = dict(request["headers"])63+ request_data = request["data"]64+65+ response_body = json.dumps(66+ {67+ "method": request_headers[b":method"].decode(),68+ "path": request_headers[b":path"].decode(),69+ "body": request_data.decode(),70+ }71+ ).encode()72+73+ response_headers = ((b":status", b"200"),)74+ self.conn.send_headers(stream_id, response_headers)75+ self.conn.send_data(stream_id, response_body, end_stream=True)76+ self.buffer += self.conn.data_to_send()77+78+79+@pytest.mark.asyncio80+async def test_http2_get_request():81+ server = MockServer()82+ async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:83+ response = await conn.request("GET", "http://example.org")84+ assert response.status_code == 20085+ assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}86+87+88+@pytest.mark.asyncio89+async def test_http2_post_request():90+ server = MockServer()91+ async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:92+ response = await conn.request("POST", "http://example.org", content=b"<data>")93+ assert response.status_code == 20094+ assert json.loads(response.content) == {95+ "method": "POST",96+ "path": "/",97+ "body": "<data>",98+ }99+100+101+@pytest.mark.asyncio102+async def test_http2_multiple_requests():103+ server = MockServer()104+ async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:105+ response_1 = await conn.request("GET", "http://example.org/1")106+ response_2 = await conn.request("GET", "http://example.org/2")107+ response_3 = await conn.request("GET", "http://example.org/3")108+109+ assert response_1.status_code == 200110+ assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}111+112+ assert response_2.status_code == 200113+ assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}114+115+ assert response_3.status_code == 200116+ assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}added:tests/models/test_headers.py+154 added
1+import httpcore2+3+4+def test_headers():5+ h = httpcore.Headers([("a", "123"), ("a", "456"), ("b", "789")])6+ assert "a" in h7+ assert "A" in h8+ assert "b" in h9+ assert "B" in h10+ assert "c" not in h11+ assert h["a"] == "123, 456"12+ assert h.get("a") == "123, 456"13+ assert h.get("nope", default=None) is None14+ assert h.getlist("a") == ["123", "456"]15+ assert h.keys() == ["a", "a", "b"]16+ assert h.values() == ["123", "456", "789"]17+ assert h.items() == [("a", "123"), ("a", "456"), ("b", "789")]18+ assert list(h) == ["a", "a", "b"]19+ assert dict(h) == {"a": "123, 456", "b": "789"}20+ assert repr(h) == "Headers([('a', '123'), ('a', '456'), ('b', '789')])"21+ assert h == httpcore.Headers([("a", "123"), ("b", "789"), ("a", "456")])22+ assert h != [("a", "123"), ("A", "456"), ("b", "789")]23+24+ h = httpcore.Headers({"a": "123", "b": "789"})25+ assert h["A"] == "123"26+ assert h["B"] == "789"27+ assert h.raw == [(b"a", b"123"), (b"b", b"789")]28+ assert repr(h) == "Headers({'a': '123', 'b': '789'})"29+30+31+def test_header_mutations():32+ h = httpcore.Headers()33+ assert dict(h) == {}34+ h["a"] = "1"35+ assert dict(h) == {"a": "1"}36+ h["a"] = "2"37+ assert dict(h) == {"a": "2"}38+ h.setdefault("a", "3")39+ assert dict(h) == {"a": "2"}40+ h.setdefault("b", "4")41+ assert dict(h) == {"a": "2", "b": "4"}42+ del h["a"]43+ assert dict(h) == {"b": "4"}44+ assert h.raw == [(b"b", b"4")]45+46+47+def test_copy_headers():48+ headers = httpcore.Headers({"custom": "example"})49+ headers_copy = httpcore.Headers(headers)50+ assert headers == headers_copy51+52+53+def test_headers_insert_retains_ordering():54+ headers = httpcore.Headers({"a": "a", "b": "b", "c": "c"})55+ headers["b"] = "123"56+ assert list(headers.values()) == ["a", "123", "c"]57+58+59+def test_headers_insert_appends_if_new():60+ headers = httpcore.Headers({"a": "a", "b": "b", "c": "c"})61+ headers["d"] = "123"62+ assert list(headers.values()) == ["a", "b", "c", "123"]63+64+65+def test_headers_insert_removes_all_existing():66+ headers = httpcore.Headers([("a", "123"), ("a", "456")])67+ headers["a"] = "789"68+ assert dict(headers) == {"a": "789"}69+70+71+def test_headers_delete_removes_all_existing():72+ headers = httpcore.Headers([("a", "123"), ("a", "456")])73+ del headers["a"]74+ assert dict(headers) == {}75+76+77+def test_headers_dict_repr():78+ """79+ Headers should display with a dict repr by default.80+ """81+ headers = httpcore.Headers({"custom": "example"})82+ assert repr(headers) == "Headers({'custom': 'example'})"83+84+85+def test_headers_encoding_in_repr():86+ """87+ Headers should display an encoding in the repr if required.88+ """89+ headers = httpcore.Headers({b"custom": "example ☃".encode("utf-8")})90+ assert repr(headers) == "Headers({'custom': 'example ☃'}, encoding='utf-8')"91+92+93+def test_headers_list_repr():94+ """95+ Headers should display with a list repr if they include multiple identical keys.96+ """97+ headers = httpcore.Headers([("custom", "example 1"), ("custom", "example 2")])98+ assert (99+ repr(headers) == "Headers([('custom', 'example 1'), ('custom', 'example 2')])"100+ )101+102+103+def test_headers_decode_ascii():104+ """105+ Headers should decode as ascii by default.106+ """107+ raw_headers = [(b"Custom", b"Example")]108+ headers = httpcore.Headers(raw_headers)109+ assert dict(headers) == {"custom": "Example"}110+ assert headers.encoding == "ascii"111+112+113+def test_headers_decode_utf_8():114+ """115+ Headers containing non-ascii codepoints should default to decoding as utf-8.116+ """117+ raw_headers = [(b"Custom", "Code point: ☃".encode("utf-8"))]118+ headers = httpcore.Headers(raw_headers)119+ assert dict(headers) == {"custom": "Code point: ☃"}120+ assert headers.encoding == "utf-8"121+122+123+def test_headers_decode_iso_8859_1():124+ """125+ Headers containing non-UTF-8 codepoints should default to decoding as iso-8859-1.126+ """127+ raw_headers = [(b"Custom", "Code point: ÿ".encode("iso-8859-1"))]128+ headers = httpcore.Headers(raw_headers)129+ assert dict(headers) == {"custom": "Code point: ÿ"}130+ assert headers.encoding == "iso-8859-1"131+132+133+def test_headers_decode_explicit_encoding():134+ """135+ An explicit encoding may be set on headers in order to force a136+ particular decoding.137+ """138+ raw_headers = [(b"Custom", "Code point: ☃".encode("utf-8"))]139+ headers = httpcore.Headers(raw_headers)140+ headers.encoding = "iso-8859-1"141+ print(headers)142+ assert dict(headers) == {"custom": "Code point: â\x98\x83"}143+ assert headers.encoding == "iso-8859-1"144+145+146+def test_multiple_headers():147+ """148+ Most headers should split by commas for `getlist`, except 'Set-Cookie'.149+ """150+ h = httpcore.Headers([("set-cookie", "a, b"), ("set-cookie", "c")])151+ h.getlist("Set-Cookie") == ["a, b", "b"]152+153+ h = httpcore.Headers([("vary", "a, b"), ("vary", "c")])154+ h.getlist("Vary") == ["a", "b", "c"]added:tests/models/test_requests.py+103 added
1+import pytest2+3+import httpcore4+5+6+def test_host_header():7+ request = httpcore.Request("GET", "http://example.org")8+ request.prepare()9+ assert request.headers == httpcore.Headers(10+ [(b"host", b"example.org"), (b"accept-encoding", b"deflate, gzip, br")]11+ )12+13+14+def test_content_length_header():15+ request = httpcore.Request("POST", "http://example.org", content=b"test 123")16+ request.prepare()17+ assert request.headers == httpcore.Headers(18+ [19+ (b"host", b"example.org"),20+ (b"content-length", b"8"),21+ (b"accept-encoding", b"deflate, gzip, br"),22+ ]23+ )24+25+26+def test_transfer_encoding_header():27+ async def streaming_body(data):28+ yield data # pragma: nocover29+30+ content = streaming_body(b"test 123")31+32+ request = httpcore.Request("POST", "http://example.org", content=content)33+ request.prepare()34+ assert request.headers == httpcore.Headers(35+ [36+ (b"host", b"example.org"),37+ (b"transfer-encoding", b"chunked"),38+ (b"accept-encoding", b"deflate, gzip, br"),39+ ]40+ )41+42+43+def test_override_host_header():44+ headers = [(b"host", b"1.2.3.4:80")]45+46+ request = httpcore.Request("GET", "http://example.org", headers=headers)47+ request.prepare()48+ assert request.headers == httpcore.Headers(49+ [(b"accept-encoding", b"deflate, gzip, br"), (b"host", b"1.2.3.4:80")]50+ )51+52+53+def test_override_accept_encoding_header():54+ headers = [(b"accept-encoding", b"identity")]55+56+ request = httpcore.Request("GET", "http://example.org", headers=headers)57+ request.prepare()58+ assert request.headers == httpcore.Headers(59+ [(b"host", b"example.org"), (b"accept-encoding", b"identity")]60+ )61+62+63+def test_override_content_length_header():64+ async def streaming_body(data):65+ yield data # pragma: nocover66+67+ content = streaming_body(b"test 123")68+ headers = [(b"content-length", b"8")]69+70+ request = httpcore.Request(71+ "POST", "http://example.org", content=content, headers=headers72+ )73+ request.prepare()74+ assert request.headers == httpcore.Headers(75+ [76+ (b"host", b"example.org"),77+ (b"accept-encoding", b"deflate, gzip, br"),78+ (b"content-length", b"8"),79+ ]80+ )81+82+83+def test_url():84+ request = httpcore.Request("GET", "http://example.org")85+ assert request.url.scheme == "http"86+ assert request.url.port == 8087+ assert request.url.full_path == "/"88+89+ request = httpcore.Request("GET", "https://example.org/abc?foo=bar")90+ assert request.url.scheme == "https"91+ assert request.url.port == 44392+ assert request.url.full_path == "/abc?foo=bar"93+94+95+def test_invalid_urls():96+ with pytest.raises(httpcore.InvalidURL):97+ httpcore.Request("GET", "example.org")98+99+ with pytest.raises(httpcore.InvalidURL):100+ httpcore.Request("GET", "invalid://example.org")101+102+ with pytest.raises(httpcore.InvalidURL):103+ httpcore.Request("GET", "http:///foo")added:tests/models/test_responses.py+148 added
1+import pytest2+3+import httpcore4+5+6+async def streaming_body():7+ yield b"Hello, "8+ yield b"world!"9+10+11+def test_response():12+ response = httpcore.Response(200, content=b"Hello, world!")13+ assert response.status_code == 20014+ assert response.reason_phrase == "OK"15+ assert response.text == "Hello, world!"16+17+18+def test_response_content_type_encoding():19+ headers = {"Content-Type": "text-plain; charset=latin-1"}20+ response = httpcore.Response(21+ 200, content="Latin 1: ÿ".encode("latin-1"), headers=headers22+ )23+ assert response.text == "Latin 1: ÿ"24+ assert response.encoding == "latin-1"25+26+27+def test_response_autodetect_encoding():28+ response = httpcore.Response(200, content="Snowmen: ☃☃☃".encode("utf-8"))29+ assert response.text == "Snowmen: ☃☃☃"30+ assert response.encoding == "utf-8"31+32+33+def test_response_default_encoding():34+ response = httpcore.Response(200, content=b"")35+ assert response.text == ""36+ assert response.encoding == "utf-8"37+38+39+def test_response_set_explicit_encoding():40+ headers = {41+ "Content-Type": "text-plain; charset=utf-8"42+ } # Deliberately incorrect charset43+ response = httpcore.Response(44+ 200, content="Latin 1: ÿ".encode("latin-1"), headers=headers45+ )46+ response.encoding = "latin-1"47+ assert response.text == "Latin 1: ÿ"48+ assert response.encoding == "latin-1"49+50+51+def test_response_force_encoding():52+ response = httpcore.Response(200, content="Snowman: ☃".encode("utf-8"))53+ response.encoding = "iso-8859-1"54+ assert response.status_code == 20055+ assert response.reason_phrase == "OK"56+ assert response.text == "Snowman: â\x98\x83"57+ assert response.encoding == "iso-8859-1"58+59+60+@pytest.mark.asyncio61+async def test_read_response():62+ response = httpcore.Response(200, content=b"Hello, world!")63+64+ assert response.status_code == 20065+ assert response.text == "Hello, world!"66+ assert response.encoding == "ascii"67+ assert response.is_closed68+69+ content = await response.read()70+71+ assert content == b"Hello, world!"72+ assert response.content == b"Hello, world!"73+ assert response.is_closed74+75+76+@pytest.mark.asyncio77+async def test_raw_interface():78+ response = httpcore.Response(200, content=b"Hello, world!")79+80+ raw = b""81+ async for part in response.raw():82+ raw += part83+ assert raw == b"Hello, world!"84+85+86+@pytest.mark.asyncio87+async def test_stream_interface():88+ response = httpcore.Response(200, content=b"Hello, world!")89+90+ content = b""91+ async for part in response.stream():92+ content += part93+ assert content == b"Hello, world!"94+95+96+@pytest.mark.asyncio97+async def test_stream_interface_after_read():98+ response = httpcore.Response(200, content=b"Hello, world!")99+100+ await response.read()101+102+ content = b""103+ async for part in response.stream():104+ content += part105+ assert content == b"Hello, world!"106+107+108+@pytest.mark.asyncio109+async def test_streaming_response():110+ response = httpcore.Response(200, content=streaming_body())111+112+ assert response.status_code == 200113+ assert not response.is_closed114+115+ content = await response.read()116+117+ assert content == b"Hello, world!"118+ assert response.content == b"Hello, world!"119+ assert response.is_closed120+121+122+@pytest.mark.asyncio123+async def test_cannot_read_after_stream_consumed():124+ response = httpcore.Response(200, content=streaming_body())125+126+ content = b""127+ async for part in response.stream():128+ content += part129+130+ with pytest.raises(httpcore.StreamConsumed):131+ await response.read()132+133+134+@pytest.mark.asyncio135+async def test_cannot_read_after_response_closed():136+ response = httpcore.Response(200, content=streaming_body())137+138+ await response.close()139+140+ with pytest.raises(httpcore.ResponseClosed):141+ await response.read()142+143+144+def test_unknown_status_code():145+ response = httpcore.Response(600)146+ assert response.status_code == 600147+ assert response.reason_phrase == ""148+ assert response.text == ""deleted:tests/test_api.py-43 removed
1-import pytest2-3-import httpcore4-5-6-@pytest.mark.asyncio7-async def test_get(server):8- async with httpcore.ConnectionPool() as http:9- response = await http.request("GET", "http://127.0.0.1:8000/")10- assert response.status_code == 20011- assert response.body == b"Hello, world!"12-13-14-@pytest.mark.asyncio15-async def test_post(server):16- async with httpcore.ConnectionPool() as http:17- response = await http.request(18- "POST", "http://127.0.0.1:8000/", body=b"Hello, world!"19- )20- assert response.status_code == 20021-22-23-@pytest.mark.asyncio24-async def test_stream_response(server):25- async with httpcore.ConnectionPool() as http:26- response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)27- assert response.status_code == 20028- assert not hasattr(response, "body")29- body = await response.read()30- assert body == b"Hello, world!"31-32-33-@pytest.mark.asyncio34-async def test_stream_request(server):35- async def hello_world():36- yield b"Hello, "37- yield b"world!"38-39- async with httpcore.ConnectionPool() as http:40- response = await http.request(41- "POST", "http://127.0.0.1:8000/", body=hello_world()42- )43- assert response.status_code == 200added:tests/test_client.py+52 added
1+import pytest2+3+import httpcore4+5+6+@pytest.mark.asyncio7+async def test_get(server):8+ url = "http://127.0.0.1:8000/"9+ async with httpcore.Client() as client:10+ response = await client.get(url)11+ assert response.status_code == 20012+ assert response.text == "Hello, world!"13+14+15+@pytest.mark.asyncio16+async def test_post(server):17+ url = "http://127.0.0.1:8000/"18+ async with httpcore.Client() as client:19+ response = await client.post(url, content=b"Hello, world!")20+ assert response.status_code == 20021+22+23+@pytest.mark.asyncio24+async def test_stream_response(server):25+ async with httpcore.Client() as client:26+ response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)27+ assert response.status_code == 20028+ body = await response.read()29+ assert body == b"Hello, world!"30+ assert response.content == b"Hello, world!"31+32+33+@pytest.mark.asyncio34+async def test_access_content_stream_response(server):35+ async with httpcore.Client() as client:36+ response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)37+ assert response.status_code == 20038+ with pytest.raises(httpcore.ResponseNotRead):39+ response.content40+41+42+@pytest.mark.asyncio43+async def test_stream_request(server):44+ async def hello_world():45+ yield b"Hello, "46+ yield b"world!"47+48+ async with httpcore.Client() as client:49+ response = await client.request(50+ "POST", "http://127.0.0.1:8000/", content=hello_world()51+ )52+ assert response.status_code == 200modified:tests/test_config.py+22 added-23 removed
1+import ssl2+3+import pytest4+5 import httpcore6 7 8+@pytest.mark.asyncio9+async def test_load_ssl_config():10+ ssl_config = httpcore.SSLConfig()11+ context = await ssl_config.load_ssl_context()12+ assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED13+14+15+@pytest.mark.asyncio16+async def test_load_ssl_config_no_verify(verify=False):17+ ssl_config = httpcore.SSLConfig(verify=False)18+ context = await ssl_config.load_ssl_context()19+ assert context.verify_mode == ssl.VerifyMode.CERT_NONE20+21+22 def test_ssl_repr():23 ssl = httpcore.SSLConfig(verify=False)24 assert repr(ssl) == "SSLConfig(cert=None, verify=False)"25 4 unmodified lines30 31 timeout = httpcore.TimeoutConfig(read_timeout=5.0)32 assert (33 repr(timeout)16- == "TimeoutConfig(connect_timeout=None, read_timeout=5.0, pool_timeout=None)"34+ == "TimeoutConfig(connect_timeout=None, read_timeout=5.0, write_timeout=None)"35 )36 37 38 def test_limits_repr():39 limits = httpcore.PoolLimits(hard_limit=100)22- assert repr(limits) == "PoolLimits(soft_limit=None, hard_limit=100)"40+ assert (41+ repr(limits) == "PoolLimits(soft_limit=None, hard_limit=100, pool_timeout=None)"42+ )43 44 45 def test_ssl_eq():46 ssl = httpcore.SSLConfig(verify=False)7 unmodified lines54 55 def test_limits_eq():56 limits = httpcore.PoolLimits(hard_limit=100)57 assert limits == httpcore.PoolLimits(hard_limit=100)38-39-40-def test_ssl_hash():41- cache = {}42- ssl = httpcore.SSLConfig(verify=False)43- cache[ssl] = "example"44- assert cache[httpcore.SSLConfig(verify=False)] == "example"45-46-47-def test_timeout_hash():48- cache = {}49- timeout = httpcore.TimeoutConfig(timeout=5.0)50- cache[timeout] = "example"51- assert cache[httpcore.TimeoutConfig(timeout=5.0)] == "example"52-53-54-def test_limits_hash():55- cache = {}56- limits = httpcore.PoolLimits(hard_limit=100)57- cache[limits] = "example"58- assert cache[httpcore.PoolLimits(hard_limit=100)] == "example"deleted:tests/test_connection_pools.py-126 removed
1-import pytest2-3-import httpcore4-5-6-@pytest.mark.asyncio7-async def test_keepalive_connections(server):8- """9- Connections should default to staying in a keep-alive state.10- """11- async with httpcore.ConnectionPool() as http:12- response = await http.request("GET", "http://127.0.0.1:8000/")13- assert http.num_active_connections == 014- assert http.num_keepalive_connections == 115-16- response = await http.request("GET", "http://127.0.0.1:8000/")17- assert http.num_active_connections == 018- assert http.num_keepalive_connections == 119-20-21-@pytest.mark.asyncio22-async def test_differing_connection_keys(server):23- """24- Connnections to differing connection keys should result in multiple connections.25- """26- async with httpcore.ConnectionPool() as http:27- response = await http.request("GET", "http://127.0.0.1:8000/")28- assert http.num_active_connections == 029- assert http.num_keepalive_connections == 130-31- response = await http.request("GET", "http://localhost:8000/")32- assert http.num_active_connections == 033- assert http.num_keepalive_connections == 234-35-36-@pytest.mark.asyncio37-async def test_soft_limit(server):38- """39- The soft_limit config should limit the maximum number of keep-alive connections.40- """41- limits = httpcore.PoolLimits(soft_limit=1)42-43- async with httpcore.ConnectionPool(limits=limits) as http:44- response = await http.request("GET", "http://127.0.0.1:8000/")45- assert http.num_active_connections == 046- assert http.num_keepalive_connections == 147-48- response = await http.request("GET", "http://localhost:8000/")49- assert http.num_active_connections == 050- assert http.num_keepalive_connections == 151-52-53-@pytest.mark.asyncio54-async def test_streaming_response_holds_connection(server):55- """56- A streaming request should hold the connection open until the response is read.57- """58- async with httpcore.ConnectionPool() as http:59- response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)60- assert http.num_active_connections == 161- assert http.num_keepalive_connections == 062-63- await response.read()64-65- assert http.num_active_connections == 066- assert http.num_keepalive_connections == 167-68-69-@pytest.mark.asyncio70-async def test_multiple_concurrent_connections(server):71- """72- Multiple conncurrent requests should open multiple conncurrent connections.73- """74- async with httpcore.ConnectionPool() as http:75- response_a = await http.request("GET", "http://127.0.0.1:8000/", stream=True)76- assert http.num_active_connections == 177- assert http.num_keepalive_connections == 078-79- response_b = await http.request("GET", "http://127.0.0.1:8000/", stream=True)80- assert http.num_active_connections == 281- assert http.num_keepalive_connections == 082-83- await response_b.read()84- assert http.num_active_connections == 185- assert http.num_keepalive_connections == 186-87- await response_a.read()88- assert http.num_active_connections == 089- assert http.num_keepalive_connections == 290-91-92-@pytest.mark.asyncio93-async def test_close_connections(server):94- """95- Using a `Connection: close` header should close the connection.96- """97- headers = [(b"connection", b"close")]98- async with httpcore.ConnectionPool() as http:99- response = await http.request("GET", "http://127.0.0.1:8000/", headers=headers)100- assert http.num_active_connections == 0101- assert http.num_keepalive_connections == 0102-103-104-@pytest.mark.asyncio105-async def test_standard_response_close(server):106- """107- A standard close should keep the connection open.108- """109- async with httpcore.ConnectionPool() as http:110- response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)111- await response.read()112- await response.close()113- assert http.num_active_connections == 0114- assert http.num_keepalive_connections == 1115-116-117-@pytest.mark.asyncio118-async def test_premature_response_close(server):119- """120- A premature close should close the connection.121- """122- async with httpcore.ConnectionPool() as http:123- response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)124- await response.close()125- assert http.num_active_connections == 0126- assert http.num_keepalive_connections == 0deleted:tests/test_connections.py-20 removed
1-import pytest2-3-import httpcore4-5-6-@pytest.mark.asyncio7-async def test_get(server):8- http = httpcore.HTTP11Connection(origin="http://127.0.0.1:8000/")9- response = await http.request("GET", "http://127.0.0.1:8000/")10- assert response.status_code == 20011- assert response.body == b"Hello, world!"12-13-14-@pytest.mark.asyncio15-async def test_post(server):16- http = httpcore.HTTP11Connection(origin="http://127.0.0.1:8000/")17- response = await http.request(18- "POST", "http://127.0.0.1:8000/", body=b"Hello, world!"19- )20- assert response.status_code == 200added:tests/test_decoders.py+89 added
1+import zlib2+3+import brotli4+import pytest5+6+import httpcore7+8+9+def test_deflate():10+ body = b"test 123"11+ compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)12+ compressed_body = compressor.compress(body) + compressor.flush()13+14+ headers = [(b"Content-Encoding", b"deflate")]15+ response = httpcore.Response(200, headers=headers, content=compressed_body)16+ assert response.content == body17+18+19+def test_gzip():20+ body = b"test 123"21+ compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)22+ compressed_body = compressor.compress(body) + compressor.flush()23+24+ headers = [(b"Content-Encoding", b"gzip")]25+ response = httpcore.Response(200, headers=headers, content=compressed_body)26+ assert response.content == body27+28+29+def test_brotli():30+ body = b"test 123"31+ compressed_body = brotli.compress(body)32+33+ headers = [(b"Content-Encoding", b"br")]34+ response = httpcore.Response(200, headers=headers, content=compressed_body)35+ assert response.content == body36+37+38+def test_multi():39+ body = b"test 123"40+41+ deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)42+ compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()43+44+ gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)45+ compressed_body = (46+ gzip_compressor.compress(compressed_body) + gzip_compressor.flush()47+ )48+49+ headers = [(b"Content-Encoding", b"deflate, gzip")]50+ response = httpcore.Response(200, headers=headers, content=compressed_body)51+ assert response.content == body52+53+54+def test_multi_with_identity():55+ body = b"test 123"56+ compressed_body = brotli.compress(body)57+58+ headers = [(b"Content-Encoding", b"br, identity")]59+ response = httpcore.Response(200, headers=headers, content=compressed_body)60+ assert response.content == body61+62+ headers = [(b"Content-Encoding", b"identity, br")]63+ response = httpcore.Response(200, headers=headers, content=compressed_body)64+ assert response.content == body65+66+67+@pytest.mark.asyncio68+async def test_streaming():69+ body = b"test 123"70+ compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)71+72+ async def compress(body):73+ yield compressor.compress(body)74+ yield compressor.flush()75+76+ headers = [(b"Content-Encoding", b"gzip")]77+ response = httpcore.Response(200, headers=headers, content=compress(body))78+ assert not hasattr(response, "body")79+ assert await response.read() == body80+81+82+@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))83+def test_decoding_errors(header_value):84+ headers = [(b"Content-Encoding", header_value)]85+ body = b"test 123"86+ compressed_body = brotli.compress(body)[3:]87+ with pytest.raises(httpcore.exceptions.DecodingError):88+ response = httpcore.Response(200, headers=headers, content=compressed_body)89+ response.contentdeleted:tests/test_decoding.py-79 removed
1-import zlib2-3-import brotli4-import pytest5-6-import httpcore7-8-9-def test_deflate():10- body = b"test 123"11- compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)12- compressed_body = compressor.compress(body) + compressor.flush()13-14- headers = [(b"Content-Encoding", b"deflate")]15- response = httpcore.Response(200, headers=headers, body=compressed_body)16- assert response.body == body17-18-19-def test_gzip():20- body = b"test 123"21- compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)22- compressed_body = compressor.compress(body) + compressor.flush()23-24- headers = [(b"Content-Encoding", b"gzip")]25- response = httpcore.Response(200, headers=headers, body=compressed_body)26- assert response.body == body27-28-29-def test_brotli():30- body = b"test 123"31- compressed_body = brotli.compress(body)32-33- headers = [(b"Content-Encoding", b"br")]34- response = httpcore.Response(200, headers=headers, body=compressed_body)35- assert response.body == body36-37-38-def test_multi():39- body = b"test 123"40-41- deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)42- compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()43-44- gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)45- compressed_body = (46- gzip_compressor.compress(compressed_body) + gzip_compressor.flush()47- )48-49- headers = [(b"Content-Encoding", b"deflate, gzip")]50- response = httpcore.Response(200, headers=headers, body=compressed_body)51- assert response.body == body52-53-54-def test_multi_with_identity():55- body = b"test 123"56- compressed_body = brotli.compress(body)57-58- headers = [(b"Content-Encoding", b"br, identity")]59- response = httpcore.Response(200, headers=headers, body=compressed_body)60- assert response.body == body61-62- headers = [(b"Content-Encoding", b"identity, br")]63- response = httpcore.Response(200, headers=headers, body=compressed_body)64- assert response.body == body65-66-67-@pytest.mark.asyncio68-async def test_streaming():69- body = b"test 123"70- compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)71-72- async def compress(body):73- yield compressor.compress(body)74- yield compressor.flush()75-76- headers = [(b"Content-Encoding", b"gzip")]77- response = httpcore.Response(200, headers=headers, body=compress(body))78- assert not hasattr(response, "body")79- assert await response.read() == bodydeleted:tests/test_requests.py-92 removed
1-import pytest2-3-import httpcore4-5-6-def test_host_header():7- request = httpcore.Request("GET", "http://example.org")8- assert request.headers == [9- (b"host", b"example.org"),10- (b"accept-encoding", b"deflate, gzip, br"),11- ]12-13-14-def test_content_length_header():15- request = httpcore.Request("POST", "http://example.org", body=b"test 123")16- assert request.headers == [17- (b"host", b"example.org"),18- (b"content-length", b"8"),19- (b"accept-encoding", b"deflate, gzip, br"),20- ]21-22-23-def test_transfer_encoding_header():24- async def streaming_body(data):25- yield data # pragma: nocover26-27- body = streaming_body(b"test 123")28-29- request = httpcore.Request("POST", "http://example.org", body=body)30- assert request.headers == [31- (b"host", b"example.org"),32- (b"transfer-encoding", b"chunked"),33- (b"accept-encoding", b"deflate, gzip, br"),34- ]35-36-37-def test_override_host_header():38- headers = [(b"host", b"1.2.3.4:80")]39-40- request = httpcore.Request("GET", "http://example.org", headers=headers)41- assert request.headers == [42- (b"accept-encoding", b"deflate, gzip, br"),43- (b"host", b"1.2.3.4:80"),44- ]45-46-47-def test_override_accept_encoding_header():48- headers = [(b"accept-encoding", b"identity")]49-50- request = httpcore.Request("GET", "http://example.org", headers=headers)51- assert request.headers == [52- (b"host", b"example.org"),53- (b"accept-encoding", b"identity"),54- ]55-56-57-def test_override_content_length_header():58- async def streaming_body(data):59- yield data # pragma: nocover60-61- body = streaming_body(b"test 123")62- headers = [(b"content-length", b"8")]63-64- request = httpcore.Request("POST", "http://example.org", body=body, headers=headers)65- assert request.headers == [66- (b"host", b"example.org"),67- (b"accept-encoding", b"deflate, gzip, br"),68- (b"content-length", b"8"),69- ]70-71-72-def test_url():73- request = httpcore.Request("GET", "http://example.org")74- assert request.url.scheme == "http"75- assert request.url.port == 8076- assert request.url.target == "/"77-78- request = httpcore.Request("GET", "https://example.org/abc?foo=bar")79- assert request.url.scheme == "https"80- assert request.url.port == 44381- assert request.url.target == "/abc?foo=bar"82-83-84-def test_invalid_urls():85- with pytest.raises(ValueError):86- httpcore.Request("GET", "example.org")87-88- with pytest.raises(ValueError):89- httpcore.Request("GET", "invalid://example.org")90-91- with pytest.raises(ValueError):92- httpcore.Request("GET", "http:///foo")deleted:tests/test_responses.py-74 removed
1-import pytest2-3-import httpcore4-5-6-async def streaming_body():7- yield b"Hello, "8- yield b"world!"9-10-11-def test_response():12- response = httpcore.Response(200, body=b"Hello, world!")13- assert response.status_code == 20014- assert response.reason == "OK"15- assert response.body == b"Hello, world!"16- assert response.is_closed17-18-19-@pytest.mark.asyncio20-async def test_read_response():21- response = httpcore.Response(200, body=b"Hello, world!")22-23- assert response.status_code == 20024- assert response.body == b"Hello, world!"25- assert response.is_closed26-27- body = await response.read()28-29- assert body == b"Hello, world!"30- assert response.body == b"Hello, world!"31- assert response.is_closed32-33-34-@pytest.mark.asyncio35-async def test_streaming_response():36- response = httpcore.Response(200, body=streaming_body())37-38- assert response.status_code == 20039- assert not hasattr(response, "body")40- assert not response.is_closed41-42- body = await response.read()43-44- assert body == b"Hello, world!"45- assert response.body == b"Hello, world!"46- assert response.is_closed47-48-49-@pytest.mark.asyncio50-async def test_cannot_read_after_stream_consumed():51- response = httpcore.Response(200, body=streaming_body())52-53- body = b""54- async for part in response.stream():55- body += part56-57- with pytest.raises(httpcore.StreamConsumed):58- await response.read()59-60-61-@pytest.mark.asyncio62-async def test_cannot_read_after_response_closed():63- response = httpcore.Response(200, body=streaming_body())64-65- await response.close()66-67- with pytest.raises(httpcore.ResponseClosed):68- await response.read()69-70-71-def test_unknown_status_code():72- response = httpcore.Response(600)73- assert response.status_code == 60074- assert response.reason == ""modified:tests/test_sync.py+4 added-5 removed
26 unmodified lines27 def test_get(server):28 with httpcore.SyncConnectionPool() as http:29 response = http.request("GET", "http://127.0.0.1:8000/")30 assert response.status_code == 20031- assert response.body == b"Hello, world!"31+ assert response.content == b"Hello, world!"32 33 34 @threadpool35 def test_post(server):6 unmodified lines42 def test_stream_response(server):43 with httpcore.SyncConnectionPool() as http:44 response = http.request("GET", "http://127.0.0.1:8000/", stream=True)45 assert response.status_code == 20046- assert not hasattr(response, "body")47- body = response.read()48- assert body == b"Hello, world!"46+ content = response.read()47+ assert content == b"Hello, world!"48 49 50 @threadpool51 def test_stream_iterator(server):52 with httpcore.SyncConnectionPool() as http:53 response = http.request("GET", "http://127.0.0.1:8000/", stream=True)54 assert response.status_code == 20056- body = b""55+ content = b""56 for chunk in response.stream():57 body += chunk58 assert body == b"Hello, world!"59 10 unmodified linesmodified:tests/test_timeouts.py+2 added-3 removed
22 unmodified lines23 24 25 @pytest.mark.asyncio26 async def test_pool_timeout(server):27- timeout = httpcore.TimeoutConfig(pool_timeout=0.0001)28- limits = httpcore.PoolLimits(hard_limit=1)27+ limits = httpcore.PoolLimits(hard_limit=1, pool_timeout=0.0001)28 30- async with httpcore.ConnectionPool(timeout=timeout, limits=limits) as http:29+ async with httpcore.ConnectionPool(limits=limits) as http:30 response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)31 32 with pytest.raises(httpcore.PoolTimeout):33 await http.request("GET", "http://localhost:8000/")2 unmodified linesadded:API.md+90 added
1+Client(...)2+3+ .request(method, url, ...)4+5+ .get(url, ...)6+ .options(url, ...)7+ .head(url, ...)8+ .post(url, ...)9+ .put(url, ...)10+ .patch(url, ...)11+ .delete(url, ...)12+13+ .prepare_request(request)14+ .send(request, ...)15+ .close()16+17+18+Adapter()19+20+ .prepare_request(request)21+ .send(request)22+ .close()23+24+25++ EnvironmentAdapter26++ RedirectAdapter27++ CookieAdapter28++ AuthAdapter29++ ConnectionPool30+ + HTTPConnection31+ + HTTP11Connection32+ + HTTP2Connection33+34+35+36+Response(...)37+ .status_code - int38+ .reason_phrase - str39+ .protocol - "HTTP/2" or "HTTP/1.1"40+ .url - URL41+ .headers - Headers42+43+ .content - bytes44+ .text - str45+ .encoding - str46+ .json() - Any47+48+ .read() - bytes49+ .stream() - bytes iterator50+ .raw() - bytes iterator51+ .close() - None52+53+ .is_redirect - bool54+ .request - Request55+ .cookies - Cookies56+ .history - List[Response]57+58+ .raise_for_status()59+ .next()60+61+62+Request(...)63+ .method64+ .url65+ .headers66+67+ ...68+69+70+Headers71+72+URL73+74+Origin75+76+Cookies77+78+79+# Sync80+81+SyncClient82+SyncResponse83+SyncRequest84+SyncAdapter85+86+87+88+SSE89+HTTP/2 server push support90+Concurrencymodified:requirements.txt+3 added
1 certifi2+chardet3 h114+h25+rfc39866 7 # Optional8 brotlipy9 10 unmodified linesmodified:setup.py+1 added-1 removed
45 unmodified lines46 author="Tom Christie",47 author_email="tom@tomchristie.com",48 packages=get_packages("httpcore"),49 data_files=[("", ["LICENSE.md"])],50- install_requires=["h11", "certifi"],50+ install_requires=["h11", "h2", "certifi", "chardet", "rfc3986"],51 classifiers=[52 "Development Status :: 3 - Alpha",53 "Environment :: Web Environment",54 "Intended Audience :: Developers",9 unmodified lines