Skip to content
Myr

Adapters

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

authored by Tom Christie · committed by Tom Christie · parent ddf1cec · Browse files · 20 files+404 added−217 removed
This commit

State

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

Diff stats

20 files+404 added−217 removed

  • tests:+22 added−30 removed
  • other:+382 added−187 removed

20 files+404 added−217 removed

modified:httpcore/__init__.py+2 added
1from .adapters import Adapter2from .client import Client3from .config import PoolLimits, SSLConfig, TimeoutConfig4from .connection import HTTPConnection5from .connection_pool import ConnectionPool6from .exceptions import (
15 unmodified lines
added:httpcore/adapters.py+40 added
1import typing2from types import TracebackType34from .models import URL, Request, Response567class Adapter:8 async def request(9 self,10 method: str,11 url: typing.Union[str, URL],12 *,13 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),14 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",15 **options: typing.Any,16 ) -> Response:17 request = Request(method, url, headers=headers, body=body)18 self.prepare_request(request)19 response = await self.send(request, **options)20 return response2122 def prepare_request(self, request: Request) -> None:23 raise NotImplementedError() # pragma: nocover2425 async def send(self, request: Request, **options: typing.Any) -> Response:26 raise NotImplementedError() # pragma: nocover2728 async def close(self) -> None:29 raise NotImplementedError() # pragma: nocover3031 async def __aenter__(self) -> "Adapter":32 return self3334 async def __aexit__(35 self,36 exc_type: typing.Type[BaseException] = None,37 exc_value: BaseException = None,38 traceback: TracebackType = None,39 ) -> None:40 await self.close()
added:httpcore/auth.py+18 added
1import typing23from .adapters import Adapter4from .models import Request, Response567class AuthAdapter(Adapter):8 def __init__(self, dispatch: Adapter):9 self.dispatch = dispatch1011 def prepare_request(self, request: Request) -> None:12 self.dispatch.prepare_request(request)1314 async def send(self, request: Request, **options: typing.Any) -> Response:15 return await self.dispatch.send(request, **options)1617 async def close(self) -> None:18 self.dispatch.close()
added:httpcore/client.py+124 added
1import typing2from types import TracebackType34from .auth import AuthAdapter5from .config import (6 DEFAULT_MAX_REDIRECTS,7 DEFAULT_POOL_LIMITS,8 DEFAULT_SSL_CONFIG,9 DEFAULT_TIMEOUT_CONFIG,10 PoolLimits,11 SSLConfig,12 TimeoutConfig,13)14from .connection_pool import ConnectionPool15from .cookies import CookieAdapter16from .environment import EnvironmentAdapter17from .models import URL, Request, Response18from .redirects import RedirectAdapter192021class 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 = AuthAdapter(dispatch=cookie_adapter)32 redirect_adapter = RedirectAdapter(33 dispatch=auth_adapter, max_redirects=max_redirects34 )35 self.adapter = EnvironmentAdapter(dispatch=redirect_adapter)3637 async def request(38 self,39 method: str,40 url: typing.Union[str, URL],41 *,42 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",43 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),44 stream: bool = False,45 allow_redirects: bool = True,46 ssl: typing.Optional[SSLConfig] = None,47 timeout: typing.Optional[TimeoutConfig] = None,48 ) -> Response:49 request = Request(method, url, headers=headers, body=body)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 response5960 async def get(61 self,62 url: typing.Union[str, URL],63 *,64 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),65 stream: bool = False,66 ssl: typing.Optional[SSLConfig] = None,67 timeout: typing.Optional[TimeoutConfig] = None,68 ) -> Response:69 return await self.request(70 "GET", url, headers=headers, stream=stream, ssl=ssl, timeout=timeout71 )7273 async def post(74 self,75 url: typing.Union[str, URL],76 *,77 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",78 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),79 stream: bool = False,80 ssl: typing.Optional[SSLConfig] = None,81 timeout: typing.Optional[TimeoutConfig] = None,82 ) -> Response:83 return await self.request(84 "POST",85 url,86 body=body,87 headers=headers,88 stream=stream,89 ssl=ssl,90 timeout=timeout,91 )9293 def prepare_request(self, request: Request) -> None:94 self.adapter.prepare_request(request)9596 async def send(97 self,98 request: Request,99 *,100 stream: bool = False,101 allow_redirects: bool = True,102 ssl: typing.Optional[SSLConfig] = None,103 timeout: typing.Optional[TimeoutConfig] = None,104 ) -> Response:105 options = {"stream": stream} # type: typing.Dict[str, typing.Any]106 if ssl is not None:107 options["ssl"] = ssl108 if timeout is not None:109 options["timeout"] = timeout110 return await self.adapter.send(request, **options)111112 async def close(self) -> None:113 await self.adapter.close()114115 async def __aenter__(self) -> "Client":116 return self117118 async def __aexit__(119 self,120 exc_type: typing.Type[BaseException] = None,121 exc_value: BaseException = None,122 traceback: TracebackType = None,123 ) -> None:124 await self.close()
modified:httpcore/config.py+9 added-12 removed
110 unmodified lines
111 *,112 connect_timeout: float = None,113 read_timeout: float = None,114 write_timeout: float = None,115 pool_timeout: float = None,115 ):116 if timeout is not None:117 # Specified as a single timeout value118 assert connect_timeout is None119 assert read_timeout is None120 assert write_timeout is None122 assert pool_timeout is None121 connect_timeout = timeout122 read_timeout = timeout123 write_timeout = timeout126 pool_timeout = timeout124125 self.timeout = timeout126 self.connect_timeout = connect_timeout127 self.read_timeout = read_timeout128 self.write_timeout = write_timeout132 self.pool_timeout = pool_timeout129130 def __eq__(self, other: typing.Any) -> bool:131 return (132 isinstance(other, self.__class__)133 and self.connect_timeout == other.connect_timeout134 and self.read_timeout == other.read_timeout135 and self.write_timeout == other.write_timeout140 and self.pool_timeout == other.pool_timeout136 )137138 def __repr__(self) -> str:139 class_name = self.__class__.__name__140 if self.timeout is not None:141 return f"{class_name}(timeout={self.timeout})"147 return f"{class_name}(connect_timeout={self.connect_timeout}, read_timeout={self.read_timeout}, write_timeout={self.write_timeout}, pool_timeout={self.pool_timeout})"142 return f"{class_name}(connect_timeout={self.connect_timeout}, read_timeout={self.read_timeout}, write_timeout={self.write_timeout})"143144145class PoolLimits:146 """
2 unmodified lines
149150 def __init__(151 self,152 *,158 soft_limit: typing.Optional[int] = None,159 hard_limit: typing.Optional[int] = None,153 soft_limit: int = None,154 hard_limit: int = None,155 pool_timeout: float = None,156 ):157 self.soft_limit = soft_limit158 self.hard_limit = hard_limit159 self.pool_timeout = pool_timeout160161 def __eq__(self, other: typing.Any) -> bool:162 return (163 isinstance(other, self.__class__)164 and self.soft_limit == other.soft_limit165 and self.hard_limit == other.hard_limit166 and self.pool_timeout == other.pool_timeout167 )168169 def __repr__(self) -> str:170 class_name = self.__class__.__name__173 return (174 f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit})"175 )171 return f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit}, pool_timeout={self.pool_timeout})"172173174DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)175DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)180DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100)176DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100, pool_timeout=5.0)177DEFAULT_CA_BUNDLE_PATH = certifi.where()178DEFAULT_MAX_REDIRECTS = 30
modified:httpcore/connection_pool.py+12 added-16 removed
1import collections.abc2import typing34from .adapters import Adapter5from .config import (6 DEFAULT_CA_BUNDLE_PATH,7 DEFAULT_POOL_LIMITS,8 DEFAULT_SSL_CONFIG,
3 unmodified lines
12 TimeoutConfig,13)14from .connection import HTTPConnection15from .exceptions import PoolTimeout15from .models import Client, Origin, Request, Response16from .models import Origin, Request, Response17from .streams import PoolSemaphore1819CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]20
60 unmodified lines
81 def __len__(self) -> int:82 return len(self.all)838484class ConnectionPool(Client):85class ConnectionPool(Adapter):86 def __init__(87 self,88 *,89 ssl: SSLConfig = DEFAULT_SSL_CONFIG,
4 unmodified lines
94 self.timeout = timeout95 self.limits = limits96 self.is_closed = False9797 self.max_connections = PoolSemaphore(limits, timeout)98 self.max_connections = PoolSemaphore(limits)99 self.keepalive_connections = ConnectionStore()100 self.active_connections = ConnectionStore()101102 @property103 def num_connections(self) -> int:104 return len(self.keepalive_connections) + len(self.active_connections)105105 async def send(106 self,107 request: Request,108 *,109 ssl: typing.Optional[SSLConfig] = None,110 timeout: typing.Optional[TimeoutConfig] = None,111 ) -> Response:112 connection = await self.acquire_connection(request.url.origin, timeout=timeout)106 def prepare_request(self, request: Request) -> None:107 pass108109 async def send(self, request: Request, **options: typing.Any) -> Response:110 connection = await self.acquire_connection(request.url.origin)111 try:114 response = await connection.send(request, ssl=ssl, timeout=timeout)112 response = await connection.send(request, **options)113 except BaseException as exc:114 self.active_connections.remove(connection)115 self.max_connections.release()116 raise exc117 return response118121 async def acquire_connection(122 self, origin: Origin, timeout: typing.Optional[TimeoutConfig] = None123 ) -> HTTPConnection:119 async def acquire_connection(self, origin: Origin) -> HTTPConnection:120 connection = self.active_connections.pop_by_origin(origin, http2_only=True)121 if connection is None:122 connection = self.keepalive_connections.pop_by_origin(origin)123124 if connection is None:129 await self.max_connections.acquire(timeout)125 await self.max_connections.acquire()126 connection = HTTPConnection(127 origin,128 ssl=self.ssl,129 timeout=self.timeout,
28 unmodified lines
modified:httpcore/connection.py+17 added-33 removed
2 unmodified lines
34import h2.connection5import h1167from .adapters import Adapter8from .config import DEFAULT_SSL_CONFIG, DEFAULT_TIMEOUT_CONFIG, SSLConfig, TimeoutConfig9from .exceptions import ConnectTimeout10from .http2 import HTTP2Connection11from .http11 import HTTP11Connection11from .models import Client, Origin, Request, Response12from .models import Origin, Request, Response13from .streams import Protocol, connect1415# Callback signature: async def callback(conn: HTTPConnection) -> None16ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]171818class HTTPConnection(Client):19class HTTPConnection(Adapter):20 def __init__(21 self,22 origin: typing.Union[str, Origin],23 ssl: SSLConfig = DEFAULT_SSL_CONFIG,
6 unmodified lines
30 self.release_func = release_func31 self.h11_connection = None # type: typing.Optional[HTTP11Connection]32 self.h2_connection = None # type: typing.Optional[HTTP2Connection]3333 async def send(34 self,35 request: Request,36 *,37 ssl: typing.Optional[SSLConfig] = None,38 timeout: typing.Optional[TimeoutConfig] = None,39 ) -> Response:34 def prepare_request(self, request: Request) -> None:35 pass3637 async def send(self, request: Request, **options: typing.Any) -> Response:38 if self.h11_connection is None and self.h2_connection is None:41 await self.connect(ssl, timeout)39 await self.connect(**options)4041 if self.h2_connection is not None:44 response = await self.h2_connection.send(request, ssl=ssl, timeout=timeout)42 response = await self.h2_connection.send(request, **options)43 else:44 assert self.h11_connection is not None47 response = await self.h11_connection.send(request, ssl=ssl, timeout=timeout)45 response = await self.h11_connection.send(request, **options)4647 return response4851 async def connect(52 self,53 ssl: typing.Optional[SSLConfig] = None,54 timeout: typing.Optional[TimeoutConfig] = None,55 ) -> None:56 if ssl is None:57 ssl = self.ssl58 if timeout is None:59 timeout = self.timeout49 async def connect(self, **options: typing.Any) -> None:50 ssl = options.get("ssl", self.ssl)51 timeout = options.get("timeout", self.timeout)52 assert isinstance(ssl, SSLConfig)53 assert isinstance(timeout, TimeoutConfig)5455 hostname = self.origin.hostname56 port = self.origin.port57 ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None
4 unmodified lines
62 on_release = functools.partial(self.release_func, self)6364 reader, writer, protocol = await connect(hostname, port, ssl_context, timeout)65 if protocol == Protocol.HTTP_2:72 self.h2_connection = HTTP2Connection(73 reader,74 writer,75 origin=self.origin,76 timeout=self.timeout,77 on_release=on_release,78 )66 self.h2_connection = HTTP2Connection(reader, writer, on_release=on_release)67 else:68 self.h11_connection = HTTP11Connection(81 reader,82 writer,83 origin=self.origin,84 timeout=self.timeout,85 on_release=on_release,69 reader, writer, on_release=on_release70 )7172 async def close(self) -> None:73 if self.h2_connection is not None:
15 unmodified lines
added:httpcore/cookies.py+18 added
1import typing23from .adapters import Adapter4from .models import Request, Response567class CookieAdapter(Adapter):8 def __init__(self, dispatch: Adapter):9 self.dispatch = dispatch1011 def prepare_request(self, request: Request) -> None:12 self.dispatch.prepare_request(request)1314 async def send(self, request: Request, **options: typing.Any) -> Response:15 return await self.dispatch.send(request, **options)1617 async def close(self) -> None:18 self.dispatch.close()
added:httpcore/environment.py+27 added
1import typing23from .adapters import Adapter4from .models import Request, Response567class EnvironmentAdapter(Adapter):8 def __init__(self, dispatch: Adapter, trust_env: bool = True):9 self.dispatch = dispatch10 self.trust_env = trust_env1112 def prepare_request(self, request: Request) -> None:13 self.dispatch.prepare_request(request)1415 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)1920 async def close(self) -> None:21 await self.dispatch.close()2223 def merge_environment_options(self, options: dict) -> None:24 """25 Add environment options.26 """27 #  TODO
modified:httpcore/exceptions.py+6 added
26 unmodified lines
27 Timeout while waiting to acquire a connection from the pool.28 """293031class TooManyRedirects(Exception):32 """33 Too many redirects.34 """353637class ProtocolError(Exception):38 """39 Malformed HTTP.40 """
14 unmodified lines
modified:httpcore/http11.py+34 added-28 removed
1import typing23import h1145from .adapters import Adapter6from .config import DEFAULT_SSL_CONFIG, DEFAULT_TIMEOUT_CONFIG, SSLConfig, TimeoutConfig7from .exceptions import ConnectTimeout, ReadTimeout7from .models import Client, Origin, Request, Response8from .models import Request, Response9from .streams import BaseReader, BaseWriter1011H11Event = typing.Union[12 h11.Request,
12 unmodified lines
25# the `ConnectionPool.release_connection(conn: HTTPConnection)` method.26OnReleaseCallback = typing.Callable[[], typing.Awaitable[None]]272828class HTTP11Connection(Client):29class HTTP11Connection(Adapter):30 READ_NUM_BYTES = 40963132 def __init__(33 self,34 reader: BaseReader,35 writer: BaseWriter,35 origin: Origin,36 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,36 on_release: typing.Optional[OnReleaseCallback] = None,37 ):38 self.reader = reader39 self.writer = writer41 self.origin = origin42 self.timeout = timeout40 self.on_release = on_release41 self.h11_state = h11.Connection(our_role=h11.CLIENT)4246 @property47 def is_closed(self) -> bool:48 return self.h11_state.our_state in (h11.CLOSED, h11.ERROR)43 def prepare_request(self, request: Request) -> None:44 pass4550 async def send(51 self,52 request: Request,53 *,54 ssl: typing.Optional[SSLConfig] = None,55 timeout: typing.Optional[TimeoutConfig] = None56 ) -> Response:46 async def send(self, request: Request, **options: typing.Any) -> Response:47 timeout = options.get("timeout")48 stream = options.get("stream", False)49 assert timeout is None or isinstance(timeout, TimeoutConfig)5051 #  Start sending the request.52 method = request.method.encode()53 target = request.url.full_path54 headers = request.headers
19 unmodified lines
74 status_code = event.status_code75 headers = event.headers76 body = self._body_iter(timeout)7784 return Response(78 response = Response(79 status_code=status_code,80 reason=reason,81 protocol="HTTP/1.1",82 headers=headers,83 body=body,84 on_close=self.response_closed,85 )8687 if not stream:88 try:89 await response.read()90 finally:91 await response.close()9293 return response9495 async def close(self) -> None:96 event = h11.ConnectionClosed()97 try:98 # If we're in h11.MUST_CLOSE then we'll end up in h11.CLOSED.99 self.h11_state.send(event)100 except h11.ProtocolError:101 # If we're in some other state then it's a premature close,102 # and we'll end up in h11.ERROR.103 pass104105 await self.writer.close()106107 async def _body_iter(self, timeout: OptionalTimeout) -> typing.AsyncIterator[bytes]:108 event = await self._receive_event(timeout)109 while isinstance(event, h11.Data):110 yield event.data
25 unmodified lines
136137 if self.on_release is not None:138 await self.on_release()139126 async def close(self) -> None:127 event = h11.ConnectionClosed()128 try:129 # If we're in h11.MUST_CLOSE then we'll end up in h11.CLOSED.130 self.h11_state.send(event)131 except h11.ProtocolError:132 # If we're in some other state then it's a premature close,133 # and we'll end up in h11.ERROR.134 pass135136 await self.writer.close()140 @property141 def is_closed(self) -> bool:142 return self.h11_state.our_state in (h11.CLOSED, h11.ERROR)
modified:httpcore/http2.py+26 added-27 removed
2 unmodified lines
34import h2.connection5import h2.events67from .adapters import Adapter8from .config import DEFAULT_SSL_CONFIG, DEFAULT_TIMEOUT_CONFIG, SSLConfig, TimeoutConfig9from .exceptions import ConnectTimeout, ReadTimeout9from .models import Client, Origin, Request, Response10from .models import Request, Response11from .streams import BaseReader, BaseWriter1213OptionalTimeout = typing.Optional[TimeoutConfig]141515class HTTP2Connection(Client):16class HTTP2Connection(Adapter):17 READ_NUM_BYTES = 40961819 def __init__(19 self,20 reader: BaseReader,21 writer: BaseWriter,22 origin: Origin,23 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,24 on_release: typing.Callable = None,20 self, reader: BaseReader, writer: BaseWriter, on_release: typing.Callable = None21 ):22 self.reader = reader23 self.writer = writer28 self.origin = origin29 self.timeout = timeout24 self.on_release = on_release25 self.h2_state = h2.connection.H2Connection()26 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]27 self.initialized = False2835 @property36 def is_closed(self) -> bool:37 return False29 def prepare_request(self, request: Request) -> None:30 pass3139 async def send(40 self,41 request: Request,42 *,43 ssl: typing.Optional[SSLConfig] = None,44 timeout: typing.Optional[TimeoutConfig] = None45 ) -> Response:46 if timeout is None:47 timeout = self.timeout32 async def send(self, request: Request, **options: typing.Any) -> Response:33 timeout = options.get("timeout")34 stream = options.get("stream", False)35 assert timeout is None or isinstance(timeout, TimeoutConfig)3637 #  Start sending the request.38 if not self.initialized:39 self.initiate_connection()5152 #  Start sending the request.40 stream_id = await self.send_headers(request, timeout)41 self.events[stream_id] = []4243 # Send the request body.
19 unmodified lines
6364 body = self.body_iter(stream_id, timeout)65 on_close = functools.partial(self.response_closed, stream_id=stream_id)6680 return Response(67 response = Response(68 status_code=status_code,69 protocol="HTTP/2",70 headers=headers,71 body=body,72 on_close=on_close,73 )7475 if not stream:76 try:77 await response.read()78 finally:79 await response.close()8081 return response8283 async def close(self) -> None:84 await self.writer.close()8586 def initiate_connection(self) -> None:87 self.h2_state.initiate_connection()88 data_to_send = self.h2_state.data_to_send()89 self.writer.write_no_block(data_to_send)
54 unmodified lines
144145 if not self.events and self.on_release is not None:146 await self.on_release()147150 async def close(self) -> None:151 await self.writer.close()148 @property149 def is_closed(self) -> bool:150 return False
modified:httpcore/models.py+3 added-45 removed
1import http2import typing3from types import TracebackType3from urllib.parse import urlsplit45from .config import SSLConfig, TimeoutConfig6from .decoders import (
228 unmodified lines
235 self.is_closed = True236 if self.on_close is not None:237 await self.on_close()238240241class Client:242 async def request(243 self,244 method: str,245 url: typing.Union[str, URL],246 *,247 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),248 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",249 ssl: typing.Optional[SSLConfig] = None,250 timeout: typing.Optional[TimeoutConfig] = None,251 stream: bool = False,252 ) -> Response:253 request = Request(method, url, headers=headers, body=body)254 response = await self.send(request, ssl=ssl, timeout=timeout)255 if not stream:256 try:257 await response.read()258 finally:259 await response.close()260 return response261262 async def send(263 self,264 request: Request,265 *,266 ssl: typing.Optional[SSLConfig] = None,267 timeout: typing.Optional[TimeoutConfig] = None,268 ) -> Response:269 raise NotImplementedError() # pragma: nocover270271 async def close(self) -> None:272 raise NotImplementedError() # pragma: nocover273274 async def __aenter__(self) -> "Client":275 return self276277 async def __aexit__(278 self,279 exc_type: typing.Type[BaseException] = None,280 exc_value: BaseException = None,281 traceback: TracebackType = None,282 ) -> None:283 await self.close()239 @property240 def is_redirect(self) -> bool:241 return self.status_code in (301, 302, 303, 307, 308)
added:httpcore/redirects.py+35 added
1import typing23from .adapters import Adapter4from .exceptions import TooManyRedirects5from .models import Request, Response678class RedirectAdapter(Adapter):9 def __init__(self, dispatch: Adapter, max_redirects: int):10 self.dispatch = dispatch11 self.max_redirects = max_redirects1213 def prepare_request(self, request: Request) -> None:14 self.dispatch.prepare_request(request)1516 async def send(self, request: Request, **options: typing.Any) -> Response:17 allow_redirects = options.pop("allow_redirects", True)18 history = []1920 while True:21 response = await self.dispatch.send(request, **options)22 if not allow_redirects or not response.is_redirect:23 break24 history.append(response)25 if len(history) > self.max_redirects:26 raise TooManyRedirects()27 request = self.build_redirect_request(request, response)2829 return response3031 async def close(self) -> None:32 self.dispatch.close()3334 def build_redirect_request(self, request: Request, response: Response) -> Request:35 raise NotImplementedError()
modified:httpcore/streams.py+5 added-11 removed
39 unmodified lines
40 raise NotImplementedError() # pragma: no cover414243class BasePoolSemaphore:44 def __init__(self, limits: PoolLimits, timeout: TimeoutConfig):44 async def acquire(self) -> None:45 raise NotImplementedError() # pragma: no cover4647 async def acquire(self, timeout: OptionalTimeout = None) -> None:48 raise NotImplementedError() # pragma: no cover4947 def release(self) -> None:48 raise NotImplementedError() # pragma: no cover4950
45 unmodified lines
96 self.stream_writer.close()979899class PoolSemaphore(BasePoolSemaphore):103 def __init__(self, limits: PoolLimits, timeout: TimeoutConfig):100 def __init__(self, limits: PoolLimits):101 self.limits = limits105 self.timeout = timeout102103 @property104 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:105 if not hasattr(self, "_semaphore"):
3 unmodified lines
109 else:110 self._semaphore = asyncio.BoundedSemaphore(value=max_connections)111 return self._semaphore112117 async def acquire(self, timeout: OptionalTimeout = None) -> None:113 async def acquire(self) -> None:114 if self.semaphore is None:115 return116121 if timeout is None:122 timeout = self.timeout117 timeout = self.limits.pool_timeout123118 try:125 await asyncio.wait_for(self.semaphore.acquire(), timeout.pool_timeout)119 await asyncio.wait_for(self.semaphore.acquire(), timeout)120 except asyncio.TimeoutError:121 raise PoolTimeout()122123 def release(self) -> None:
33 unmodified lines
modified:httpcore/sync.py+6 added-15 removed
1import asyncio2import typing3from types import TracebackType45from .adapters import Adapter6from .config import SSLConfig, TimeoutConfig7from .connection_pool import ConnectionPool7from .models import URL, Client, Response8from .models import URL, Response91011class SyncResponse:12 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):
31 unmodified lines
44 return self._loop.run_until_complete(self._response.close())454647class SyncClient:47 def __init__(self, client: Client):48 self._client = client48 def __init__(self, adapter: Adapter):49 self._client = adapter50 self._loop = asyncio.new_event_loop()5152 def request(53 self,
1 unmodified line
55 url: typing.Union[str, URL],56 *,57 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),58 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",58 ssl: typing.Optional[SSLConfig] = None,59 timeout: typing.Optional[TimeoutConfig] = None,60 stream: bool = False,59 **options: typing.Any60 ) -> SyncResponse:61 response = self._loop.run_until_complete(63 self._client.request(64 method,65 url,66 headers=headers,67 body=body,68 ssl=ssl,69 timeout=timeout,70 stream=stream,71 )62 self._client.request(method, url, headers=headers, body=body, **options)63 )64 return SyncResponse(response, self._loop)6566 def close(self) -> None:
17 unmodified lines
modified:tests/test_api.py+8 added-8 removed
3 unmodified lines
456@pytest.mark.asyncio7async def test_get(server):8 async with httpcore.ConnectionPool() as http:9 response = await http.request("GET", "http://127.0.0.1:8000/")8 async with httpcore.Client() as client:9 response = await client.request("GET", "http://127.0.0.1:8000/")10 assert response.status_code == 20011 assert response.body == b"Hello, world!"121314@pytest.mark.asyncio15async def test_post(server):16 async with httpcore.ConnectionPool() as http:17 response = await http.request(16 async with httpcore.Client() as client:17 response = await client.request(18 "POST", "http://127.0.0.1:8000/", body=b"Hello, world!"19 )20 assert response.status_code == 200212223@pytest.mark.asyncio24async 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)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 assert not hasattr(response, "body")29 body = await response.read()30 assert body == b"Hello, world!"
4 unmodified lines
35 async def hello_world():36 yield b"Hello, "37 yield b"world!"3839 async with httpcore.ConnectionPool() as http:40 response = await http.request(39 async with httpcore.Client() as client:40 response = await client.request(41 "POST", "http://127.0.0.1:8000/", body=hello_world()42 )43 assert response.status_code == 200
modified:tests/test_config.py+4 added-2 removed
11 unmodified lines
1213 timeout = httpcore.TimeoutConfig(read_timeout=5.0)14 assert (15 repr(timeout)16 == "TimeoutConfig(connect_timeout=None, read_timeout=5.0, write_timeout=None, pool_timeout=None)"16 == "TimeoutConfig(connect_timeout=None, read_timeout=5.0, write_timeout=None)"17 )181920def test_limits_repr():21 limits = httpcore.PoolLimits(hard_limit=100)22 assert repr(limits) == "PoolLimits(soft_limit=None, hard_limit=100)"22 assert (23 repr(limits) == "PoolLimits(soft_limit=None, hard_limit=100, pool_timeout=None)"24 )252627def test_ssl_eq():28 ssl = httpcore.SSLConfig(verify=False)
11 unmodified lines
modified:tests/test_http2.py+8 added-17 removed
77 unmodified lines
7879@pytest.mark.asyncio80async def test_http2_get_request():81 server = MockServer()82 origin = httpcore.Origin("http://example.org")83 async with httpcore.HTTP2Connection(84 reader=server, writer=server, origin=origin85 ) as client:86 response = await client.request("GET", "http://example.org")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.body) == {"method": "GET", "path": "/", "body": ""}868788@pytest.mark.asyncio89async def test_http2_post_request():90 server = MockServer()94 origin = httpcore.Origin("http://example.org")95 async with httpcore.HTTP2Connection(96 reader=server, writer=server, origin=origin97 ) as client:98 response = await client.request("POST", "http://example.org", body=b"<data>")91 async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:92 response = await conn.request("POST", "http://example.org", body=b"<data>")93 assert response.status_code == 20094 assert json.loads(response.body) == {95 "method": "POST",96 "path": "/",
3 unmodified lines
100101@pytest.mark.asyncio102async def test_http2_multiple_requests():103 server = MockServer()110 origin = httpcore.Origin("http://example.org")111 async with httpcore.HTTP2Connection(112 reader=server, writer=server, origin=origin113 ) as client:114 response_1 = await client.request("GET", "http://example.org/1")115 response_2 = await client.request("GET", "http://example.org/2")116 response_3 = await client.request("GET", "http://example.org/3")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")108109 assert response_1.status_code == 200110 assert json.loads(response_1.body) == {"method": "GET", "path": "/1", "body": ""}111
5 unmodified lines
modified:tests/test_timeouts.py+2 added-3 removed
22 unmodified lines
232425@pytest.mark.asyncio26async 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)2830 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)3132 with pytest.raises(httpcore.PoolTimeout):33 await http.request("GET", "http://localhost:8000/")
2 unmodified lines