Skip to content
Myr

Connections

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 6a4376b · Browse files · 13 files+464 added−184 removed
This commit

State

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

Diff stats

13 files+464 added−184 removed

  • tests:+87 added−10 removed
  • other:+377 added−174 removed

13 files+464 added−184 removed

modified:httpcore/__init__.py+2 added-1 removed
1from .api import PoolManager, Response, request1from .config import PoolLimits, SSLConfig, TimeoutConfig2from .datastructures import URL, Request, Response3from .exceptions import ResponseClosed, StreamConsumed4from .pool import ConnectionPool56__version__ = "0.0.2"
deleted:httpcore/api.py-67 removed
1import typing2from types import TracebackType34from .config import (5 DEFAULT_POOL_LIMITS,6 DEFAULT_SSL_CONFIG,7 DEFAULT_TIMEOUT_CONFIG,8 PoolLimits,9 SSLConfig,10 TimeoutConfig,11)12from .models import Response131415async def request(16 method: str,17 url: str,18 *,19 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),20 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",21 stream: bool = False,22 ssl: SSLConfig = DEFAULT_SSL_CONFIG,23 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,24) -> Response:25 async with PoolManager(ssl=ssl, timeout=timeout) as pool:26 return await pool.request(27 method=method, url=url, headers=headers, body=body, stream=stream28 )293031class PoolManager:32 def __init__(33 self,34 *,35 ssl: SSLConfig = DEFAULT_SSL_CONFIG,36 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,37 limits: PoolLimits = DEFAULT_POOL_LIMITS,38 ):39 self.ssl = ssl40 self.timeout = timeout41 self.limits = limits42 self.is_closed = False4344 async def request(45 self,46 method: str,47 url: str,48 *,49 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),50 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",51 stream: bool = False,52 ) -> Response:53 raise NotImplementedError()5455 async def close(self) -> None:56 self.is_closed = True5758 async def __aenter__(self) -> "PoolManager":59 return self6061 async def __aexit__(62 self,63 exc_type: typing.Type[BaseException] = None,64 exc_value: BaseException = None,65 traceback: TracebackType = None,66 ) -> None:67 await self.close()
modified:httpcore/config.py+3 added
1import typing23import certifi456class SSLConfig:7 """8 SSL Configuration.9 """
43 unmodified lines
5354DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)55DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)56DEFAULT_POOL_LIMITS = PoolLimits(max_hosts=10, conns_per_host=10, hard_limit=False)57DEFAULT_CA_BUNDLE_PATH = certifi.where()
modified:httpcore/connections.py+87 added-29 removed
1from config import TimeoutConfig21import asyncio4import h112import ssl3import typing45import h1167from .config import TimeoutConfig8from .datastructures import Request, Response9from .exceptions import ConnectTimeout, ReadTimeout1011H11Event = typing.Union[12 h11.Request,13 h11.Response,14 h11.InformationalResponse,15 h11.Data,16 h11.EndOfMessage,17 h11.ConnectionClosed,18]192021class Connection:9 def __init__(self):22 def __init__(self, timeout: TimeoutConfig):23 self.reader = None24 self.writer = None25 self.state = h11.Connection(our_role=h11.CLIENT)26 self.timeout = timeout2714 async def open(self, host: str, port: int, ssl: ssl.SSLContext):28 async def open(29 self,30 hostname: str,31 port: int,32 *,33 ssl: typing.Union[bool, ssl.SSLContext] = False34 ) -> None:35 try:16 self.reader, self.writer = await asyncio.wait_for(17 asyncio.open_connection(host, port, ssl=ssl), timeout36 self.reader, self.writer = await asyncio.wait_for( # type: ignore37 asyncio.open_connection(hostname, port, ssl=ssl),38 self.timeout.connect_timeout,39 )40 except asyncio.TimeoutError:41 raise ConnectTimeout()4222 async def send(self, request: Request) -> Response:23 method = request.method43 async def send(self, request: Request, stream: bool=False) -> Response:44 method = request.method.encode()45 target = request.url.target46 host_header = (b"host", request.url.netloc.encode("ascii"))47 if request.is_streaming:48 content_length = (b"transfer-encoding", b"chunked")49 else:50 content_length = (b"content-length", str(len(request.body)).encode())5125 target = request.url.path26 if request.url.query:27 target += "?" + request.url.query52 headers = [host_header, content_length] + request.headers5329 headers = [30 ("host", request.url.netloc)31 ] += request.headers3233 # Send the request method, path/query, and headers.54 #  Start sending the request.55 event = h11.Request(method=method, target=target, headers=headers)56 await self._send_event(event)5758 # Send the request body.59 if request.is_streaming:39 async for data in request.raw():60 async for data in request.stream():61 event = h11.Data(data=data)62 await self._send_event(event)42 else:63 elif request.body:64 event = h11.Data(data=request.body)65 await self._send_event(event)6667 # Finalize sending the request.68 event = h11.EndOfMessage()48 await connection.send_event(event)69 await self._send_event(event)7050 async def _send_event(self, message):51 data = self.state.send(message)71 # Start getting the response.72 event = await self._receive_event()73 if isinstance(event, h11.InformationalResponse):74 event = await self._receive_event()75 assert isinstance(event, h11.Response)76 status_code = event.status_code77 headers = event.headers7879 if stream:80 return Response(status_code=status_code, headers=headers, body=self.body_iter())8182 #  Get the response body.83 body = b""84 event = await self._receive_event()85 while isinstance(event, h11.Data):86 body += event.data87 event = await self._receive_event()88 assert isinstance(event, h11.EndOfMessage)89 await self.close()9091 return Response(status_code=status_code, headers=headers, body=body)9293 async def body_iter(self) -> typing.Iterable[bytes]:94 event = await self._receive_event()95 while isinstance(event, h11.Data):96 yield event.data97 event = await self._receive_event()98 assert isinstance(event, h11.EndOfMessage)99 await self.close()100101 async def _send_event(self, event: H11Event) -> None:102 assert self.writer is not None103104 data = self.state.send(event)105 self.writer.write(data)10654 async def _receive_event(self, timeout):107 async def _receive_event(self) -> H11Event:108 assert self.reader is not None109110 event = self.state.next_event()11157 while type(event) is h11.NEED_DATA:112 while event is h11.NEED_DATA:113 try:59 data = await asyncio.wait_for(self.reader.read(2048), timeout)114 data = await asyncio.wait_for(115 self.reader.read(2048), self.timeout.read_timeout116 )117 except asyncio.TimeoutError:118 raise ReadTimeout()119 self.state.receive_data(data)120 event = self.state.next_event()121122 return event123124 async def close(self) -> None:67 async def close(self):68 self.writer.close()69 if hasattr(self.writer, "wait_closed"):70 await self.writer.wait_closed()125 if self.writer is not None:126 self.writer.close()127 if hasattr(self.writer, "wait_closed"):128 await self.writer.wait_closed()
added:httpcore/datastructures.py+145 added
1import typing2from urllib.parse import urlsplit34from .decoders import IdentityDecoder5from .exceptions import ResponseClosed, StreamConsumed678class URL:9 def __init__(self, url: str = "") -> None:10 self.components = urlsplit(url)11 if not self.components.scheme:12 raise ValueError("No scheme included in URL.")13 if self.components.scheme not in ("http", "https"):14 raise ValueError('URL scheme must be "http" or "https".')15 if not self.components.hostname:16 raise ValueError("No hostname included in URL.")1718 @property19 def scheme(self) -> str:20 return self.components.scheme2122 @property23 def netloc(self) -> str:24 return self.components.netloc2526 @property27 def path(self) -> str:28 return self.components.path2930 @property31 def query(self) -> str:32 return self.components.query3334 @property35 def hostname(self) -> str:36 return self.components.hostname3738 @property39 def port(self) -> int:40 port = self.components.port41 if port is None:42 return {"https": 443, "http": 80}[self.scheme]43 return port4445 @property46 def target(self) -> str:47 path = self.path or "/"48 query = self.query49 if query:50 return path + "?" + query51 return path5253 @property54 def is_secure(self) -> bool:55 return self.components.scheme == "https"565758class Request:59 def __init__(60 self,61 method: str,62 url: URL,63 *,64 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),65 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",66 ):67 self.method = method68 self.url = url69 self.headers = list(headers)70 if isinstance(body, bytes):71 self.is_streaming = False72 self.body = body73 else:74 self.is_streaming = True75 self.body_aiter = body7677 async def stream(self) -> typing.AsyncIterator[bytes]:78 assert self.is_streaming7980 async for part in self.body_aiter:81 yield part828384class Response:85 def __init__(86 self,87 status_code: int,88 *,89 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),90 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",91 on_close: typing.Callable = None,92 ):93 self.status_code = status_code94 self.headers = list(headers)95 self.on_close = on_close96 self.is_closed = False97 self.is_streamed = False98 self.decoder = IdentityDecoder()99 if isinstance(body, bytes):100 self.is_closed = True101 self.body = body102 else:103 self.body_aiter = body104105 async def read(self) -> bytes:106 """107 Read and return the response content.108 """109 if not hasattr(self, "body"):110 body = b""111 async for part in self.stream():112 body += part113 self.body = body114 return self.body115116 async def stream(self) -> typing.AsyncIterator[bytes]:117 """118 A byte-iterator over the decoded response content.119 This will allow us to handle gzip, deflate, and brotli encoded responses.120 """121 if hasattr(self, "body"):122 yield self.body123 else:124 async for chunk in self.raw():125 yield self.decoder.decode(chunk)126 yield self.decoder.flush()127128 async def raw(self) -> typing.AsyncIterator[bytes]:129 """130 A byte-iterator over the raw response content.131 """132 if self.is_streamed:133 raise StreamConsumed()134 if self.is_closed:135 raise ResponseClosed()136 self.is_streamed = True137 async for part in self.body_aiter:138 yield part139 await self.close()140141 async def close(self) -> None:142 if not self.is_closed:143 self.is_closed = True144 if self.on_close is not None:145 await self.on_close()
modified:httpcore/decoders.py+1 added-1 removed
6 unmodified lines
7 def decode(self, chunk: bytes) -> bytes:8 return chunk910 def flush(self) -> bytes:11 return b''11 return b""121314# class DeflateDecoder:15# pass
26 unmodified lines
deleted:httpcore/models.py-68 removed
1import typing23from .decoders import IdentityDecoder4from .exceptions import ResponseClosed, StreamConsumed567class Response:8 def __init__(9 self,10 status_code: int,11 *,12 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),13 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",14 on_close: typing.Callable = None,15 ):16 self.status_code = status_code17 self.headers = list(headers)18 self.on_close = on_close19 self.is_closed = False20 self.is_streamed = False21 self.decoder = IdentityDecoder()22 if isinstance(body, bytes):23 self.is_closed = True24 self.body = body25 else:26 self.body_aiter = body2728 async def read(self) -> bytes:29 """30 Read and return the response content.31 """32 if not hasattr(self, "body"):33 body = b""34 async for part in self.stream():35 body += part36 self.body = body37 return self.body3839 async def stream(self):40 """41 A byte-iterator over the decoded response content.42 This will allow us to handle gzip, deflate, and brotli encoded responses.43 """44 if hasattr(self, "body"):45 yield self.body46 else:47 async for chunk in self.raw():48 yield self.decoder.decode(chunk)49 yield self.decoder.flush()5051 async def raw(self) -> typing.AsyncIterator[bytes]:52 """53 A byte-iterator over the raw response content.54 """55 if self.is_streamed:56 raise StreamConsumed()57 if self.is_closed:58 raise ResponseClosed()59 self.is_streamed = True60 async for part in self.body_aiter():61 yield part62 await self.close()6364 async def close(self) -> None:65 if not self.is_closed:66 self.is_closed = True67 if self.on_close is not None:68 await self.on_close()
added:httpcore/pool.py+126 added
1import asyncio2import os3import ssl4import typing5from types import TracebackType67from .config import (8 DEFAULT_CA_BUNDLE_PATH,9 DEFAULT_POOL_LIMITS,10 DEFAULT_SSL_CONFIG,11 DEFAULT_TIMEOUT_CONFIG,12 PoolLimits,13 SSLConfig,14 TimeoutConfig,15)16from .connections import Connection17from .datastructures import URL, Request, Response181920class ConnectionPool:21 def __init__(22 self,23 *,24 ssl: SSLConfig = DEFAULT_SSL_CONFIG,25 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,26 limits: PoolLimits = DEFAULT_POOL_LIMITS,27 ):28 self.ssl_config = ssl29 self.timeout = timeout30 self.limits = limits31 self.is_closed = False3233 async def request(34 self,35 method: str,36 url: str,37 *,38 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),39 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",40 stream: bool = False,41 ) -> Response:42 parsed_url = URL(url)43 request = Request(method, parsed_url, headers=headers, body=body)44 ssl_context = await self.get_ssl_context(parsed_url)45 connection = await self.acquire_connection(parsed_url, ssl=ssl_context)46 response = await connection.send(request, stream=stream)47 return response4849 async def acquire_connection(50 self, url: URL, *, ssl: typing.Union[bool, ssl.SSLContext] = False51 ) -> Connection:52 connection = Connection(timeout=self.timeout)53 await connection.open(url.hostname, url.port, ssl=ssl)54 return connection5556 async def get_ssl_context(self, url: URL) -> typing.Union[bool, ssl.SSLContext]:57 if not url.is_secure:58 return False5960 if not hasattr(self, "ssl_context"):61 if not self.ssl_config.verify:62 self.ssl_context = self.get_ssl_context_no_verify()63 else:64 # Run the SSL loading in a threadpool, since it makes disk accesses.65 loop = asyncio.get_event_loop()66 self.ssl_context = await loop.run_in_executor(67 None, self.get_ssl_context_verify68 )6970 return self.ssl_context7172 def get_ssl_context_no_verify(self) -> ssl.SSLContext:73 """74 Return an SSL context for unverified connections.75 """76 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)77 context.options |= ssl.OP_NO_SSLv278 context.options |= ssl.OP_NO_SSLv379 context.options |= ssl.OP_NO_COMPRESSION80 context.set_default_verify_paths()81 return context8283 def get_ssl_context_verify(self) -> ssl.SSLContext:84 """85 Return an SSL context for verified connections.86 """87 cert = self.ssl_config.cert88 verify = self.ssl_config.verify8990 if isinstance(verify, bool):91 ca_bundle_path = DEFAULT_CA_BUNDLE_PATH92 elif os.path.exists(verify):93 ca_bundle_path = verify94 else:95 raise IOError(96 "Could not find a suitable TLS CA certificate bundle, "97 "invalid path: {}".format(verify)98 )99100 context = ssl.create_default_context()101 if os.path.isfile(ca_bundle_path):102 context.load_verify_locations(cafile=ca_bundle_path)103 elif os.path.isdir(ca_bundle_path):104 context.load_verify_locations(capath=ca_bundle_path)105106 if cert is not None:107 if isinstance(cert, str):108 context.load_cert_chain(certfile=cert)109 else:110 context.load_cert_chain(certfile=cert[0], keyfile=cert[1])111112 return context113114 async def close(self) -> None:115 self.is_closed = True116117 async def __aenter__(self) -> "ConnectionPool":118 return self119120 async def __aexit__(121 self,122 exc_type: typing.Type[BaseException] = None,123 exc_value: BaseException = None,124 traceback: TracebackType = None,125 ) -> None:126 await self.close()
added:tests/conftest.py+34 added
1import asyncio2import json34import pytest5from uvicorn.config import Config6from uvicorn.main import Server789async def app(scope, receive, send):10 assert scope['type'] == 'http'11 await send({12 'type': 'http.response.start',13 'status': 200,14 'headers': [15 [b'content-type', b'text/plain'],16 ]17 })18 await send({19 'type': 'http.response.body',20 'body': b'Hello, world!',21 })222324@pytest.fixture25async def server():26 config = Config(app=app, lifespan="off")27 server = Server(config=config)28 task = asyncio.ensure_future(server.serve())29 try:30 while not server.started:31 await asyncio.sleep(0.0001)32 yield server33 finally:34 task.cancel()
modified:tests/test_api.py+38 added
1import pytest2import httpcore345@pytest.mark.asyncio6async def test_get(server):7 async with httpcore.ConnectionPool() as http:8 response = await http.request('GET', "http://127.0.0.1:8000/")9 assert response.status_code == 20010 assert response.body == b'Hello, world!'111213@pytest.mark.asyncio14async def test_post(server):15 async with httpcore.ConnectionPool() as http:16 response = await http.request('POST', "http://127.0.0.1:8000/", body=b"Hello, world!")17 assert response.status_code == 200181920@pytest.mark.asyncio21async def test_stream_response(server):22 async with httpcore.ConnectionPool() as http:23 response = await http.request('GET', "http://127.0.0.1:8000/", stream=True)24 assert response.status_code == 20025 assert not hasattr(response, 'body')26 body = await response.read()27 assert body == b'Hello, world!'282930@pytest.mark.asyncio31async def test_stream_request(server):32 async def hello_world():33 yield b"Hello, "34 yield b"world!"3536 async with httpcore.ConnectionPool() as http:37 response = await http.request('POST', "http://127.0.0.1:8000/", body=hello_world())38 assert response.status_code == 200
modified:tests/test_responses.py+15 added-10 removed
1 unmodified line
23import httpcore456class MockRequests(httpcore.PoolManager):7 async def request(self, method, url, *, headers = (), body = b'', stream = False) -> httpcore.Response:6class MockHTTP(httpcore.ConnectionPool):7 async def request(8 self, method, url, *, headers=(), body=b"", stream=False9 ) -> httpcore.Response:10 if stream:1112 async def streaming_body():13 yield b"Hello, "14 yield b"world!"1512 return httpcore.Response(200, body=streaming_body)16 return httpcore.Response(200, body=streaming_body())17 return httpcore.Response(200, body=b"Hello, world!")181916http = MockRequests()20http = MockHTTP()212223@pytest.mark.asyncio24async def test_request():
25 unmodified lines
50 assert response.status_code == 20051 assert response.body == b"Hello, world!"52 assert response.is_closed5350 body = b''54 body = b""55 async for part in response.stream():56 body += part5758 assert body == b"Hello, world!"
5 unmodified lines
64async def test_read_streaming_response():65 response = await http.request("GET", "http://example.com", stream=True)6667 assert response.status_code == 20064 assert not hasattr(response, 'body')68 assert not hasattr(response, "body")69 assert not response.is_closed7071 body = await response.read()72
6 unmodified lines
79async def test_stream_streaming_response():80 response = await http.request("GET", "http://example.com", stream=True)8182 assert response.status_code == 20079 assert not hasattr(response, 'body')83 assert not hasattr(response, "body")84 assert not response.is_closed8582 body = b''86 body = b""87 async for part in response.stream():88 body += part8990 assert body == b"Hello, world!"87 assert not hasattr(response, 'body')91 assert not hasattr(response, "body")92 assert response.is_closed939495@pytest.mark.asyncio96async def test_cannot_read_after_stream_consumed():97 response = await http.request("GET", "http://example.com", stream=True)9895 body = b''99 body = b""100 async for part in response.stream():101 body += part102103 with pytest.raises(httpcore.StreamConsumed):104 await response.read()105106107@pytest.mark.asyncio108async def test_cannot_read_after_response_closed():109 response = await http.request("GET", "http://example.com", stream=True)110
4 unmodified lines
modified:README.md+11 added-8 removed
61 unmodified lines
6263```python64import httpcore6566http = httpcore.ConnectionPool()66response = await httpcore.request('GET', 'http://example.com')67response = await http.request('GET', 'http://example.com')68assert response.status_code == 20069assert response.body == b'Hello, world'70```7172Top-level API...7374```python75http = httpcore.ConnectionPool([ssl], [timeout], [limits])74response = await httpcore.request(method, url, [headers], [body], [stream])76response = await http.request(method, url, [headers], [body], [stream])77```7877Explicit PoolManager...79ConnectionPool as a context-manager...8081```python80async with httpcore.PoolManager([ssl], [timeout], [limits]) as pool:81 response = await pool.request(method, url, [headers], [body], [stream])82async with httpcore.ConnectionPool([ssl], [timeout], [limits]) as http:83 response = await http.request(method, url, [headers], [body], [stream])84```8586Streaming...8788```python89http = httpcore.ConnectionPool()87response = await httpcore.request(method, url, stream=True)90response = await http.request(method, url, stream=True)91async for part in response.stream():92 ...93```94
7 unmodified lines
102103class GatewayServer:104 def __init__(self, base_url):105 self.base_url = base_url103 self.pool = httpcore.PoolManager()106 self.http = httpcore.ConnectionPool()107108 async def __call__(self, scope, receive, send):109 assert scope['type'] == 'http'110 path = scope['path']
13 unmodified lines
124 yield message.get('body', b'')125 if not message.get('more_body', False):126 break127125 response = await self.pool.request(128 response = await self.http.request(129 method, url, headers=headers, body=body, stream=True130 )131132 await send({
21 unmodified lines
modified:requirements.txt+2 added
1certifi2h1134# Testing5autoflake
3 unmodified lines
9mypy10pytest11pytest-asyncio12pytest-cov13uvicorn