Skip to content
Myr

Merge pull request #1 from encode/add-connections

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

Add connections

authored by Tom Christie · committed by GitHub · parents 665743a, ba1953c · Browse files · 12 files+623 added−214 removed
This commit

State

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

Diff stats

12 files+623 added−214 removed

  • tests:+164 added−73 removed
  • other:+459 added−141 removed

12 files+623 added−214 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-132 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 .exceptions import ResponseClosed, StreamConsumed131415async 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 if stream:54 async def streaming_body():55 yield b"Hello, "56 yield b"world!"57 return Response(200, body=streaming_body)58 return Response(200, body=b"Hello, world!")5960 async def close(self) -> None:61 self.is_closed = True6263 async def __aenter__(self) -> "PoolManager":64 return self6566 async def __aexit__(67 self,68 exc_type: typing.Type[BaseException] = None,69 exc_value: BaseException = None,70 traceback: TracebackType = None,71 ) -> None:72 await self.close()737475class Response:76 def __init__(77 self,78 status_code: int,79 *,80 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),81 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",82 on_close: typing.Callable = None,83 ):84 self.status_code = status_code85 self.headers = list(headers)86 self.on_close = on_close87 self.is_closed = False88 self.is_streamed = False89 if isinstance(body, bytes):90 self.is_closed = True91 self.body = body92 else:93 self.body_aiter = body9495 async def read(self) -> bytes:96 if not hasattr(self, "body"):97 body = b""98 async for part in self.stream():99 body += part100 self.body = body101 return self.body102103 async def stream(self) -> typing.AsyncIterator[bytes]:104 if hasattr(self, "body"):105 yield self.body106 else:107 if self.is_streamed:108 raise StreamConsumed()109 if self.is_closed:110 raise ResponseClosed()111 self.is_streamed = True112 async for part in self.body_aiter():113 yield part114 await self.close()115116 async def close(self) -> None:117 if not self.is_closed:118 self.is_closed = True119 if self.on_close is not None:120 await self.on_close()121122 async def __aenter__(self) -> "Response":123 return self124125 async def __aexit__(126 self,127 exc_type: typing.Type[BaseException] = None,128 exc_value: BaseException = None,129 traceback: TracebackType = None,130 ) -> None:131 if not self.is_closed:132 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()
added:httpcore/connections.py+129 added
1import asyncio2import 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:22 def __init__(self, timeout: TimeoutConfig):23 self.reader = None24 self.writer = None25 self.state = h11.Connection(our_role=h11.CLIENT)26 self.timeout = timeout2728 async def open(29 self,30 hostname: str,31 port: int,32 *,33 ssl: typing.Union[bool, ssl.SSLContext] = False34 ) -> None:35 try:36 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()4243 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())5152 headers = [host_header, content_length] + request.headers5354 #  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:60 async for data in request.stream():61 event = h11.Data(data=data)62 await self._send_event(event)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()69 await self._send_event(event)7071 # 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 body_iter = self.body_iter()81 return Response(status_code=status_code, headers=headers, body=body_iter)8283 #  Get the response body.84 body = b""85 event = await self._receive_event()86 while isinstance(event, h11.Data):87 body += event.data88 event = await self._receive_event()89 assert isinstance(event, h11.EndOfMessage)90 await self.close()9192 return Response(status_code=status_code, headers=headers, body=body)9394 async def body_iter(self) -> typing.AsyncIterator[bytes]:95 event = await self._receive_event()96 while isinstance(event, h11.Data):97 yield event.data98 event = await self._receive_event()99 assert isinstance(event, h11.EndOfMessage)100 await self.close()101102 async def _send_event(self, event: H11Event) -> None:103 assert self.writer is not None104105 data = self.state.send(event)106 self.writer.write(data)107108 async def _receive_event(self) -> H11Event:109 assert self.reader is not None110111 event = self.state.next_event()112113 while event is h11.NEED_DATA:114 try:115 data = await asyncio.wait_for(116 self.reader.read(2048), self.timeout.read_timeout117 )118 except asyncio.TimeoutError:119 raise ReadTimeout()120 self.state.receive_data(data)121 event = self.state.next_event()122123 return event124125 async def close(self) -> None:126 if self.writer is not None:127 self.writer.close()128 if hasattr(self.writer, "wait_closed"):129 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()
added:httpcore/decoders.py+41 added
1"""2Handlers for Content-Encoding.3"""456class IdentityDecoder:7 def decode(self, chunk: bytes) -> bytes:8 return chunk910 def flush(self) -> bytes:11 return b""121314# class DeflateDecoder:15# pass16#17#18# class GZipDecoder:19# pass20#21#22# class BrotliDecoder:23# pass24#25#26# class MultiDecoder:27# def __init__(self, children):28# self.children = children29#30# def decode(self, chunk: bytes) -> bytes:31# data = chunk32# for child in children:33# data = child.decode(data)34# return data35#36# def flush(self) -> bytes:37# data = b''38# for child in children:39# data = child.decode(data)40# data = child.flush()41# return data
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+30 added
1import asyncio23import pytest4from uvicorn.config import Config5from uvicorn.main import Server678async def app(scope, receive, send):9 assert scope["type"] == "http"10 await send(11 {12 "type": "http.response.start",13 "status": 200,14 "headers": [[b"content-type", b"text/plain"]],15 }16 )17 await send({"type": "http.response.body", "body": b"Hello, world!"})181920@pytest.fixture21async def server():22 config = Config(app=app, lifespan="off")23 server = Server(config=config)24 task = asyncio.ensure_future(server.serve())25 try:26 while not server.started:27 await asyncio.sleep(0.0001)28 yield server29 finally:30 task.cancel()
modified:tests/test_api.py+20 added-73 removed
2 unmodified lines
3import httpcore456@pytest.mark.asyncio7async def test_request():8 response = await httpcore.request("GET", "http://example.com")7async 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!"11 assert response.is_closed121314@pytest.mark.asyncio15async def test_read_response():16 response = await httpcore.request("GET", "http://example.com")1715async 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 == 20019 assert response.body == b"Hello, world!"20 assert response.is_closed2122 body = await response.read()2224 assert body == b"Hello, world!"25 assert response.body == b"Hello, world!"26 assert response.is_closed272823@pytest.mark.asyncio30async def test_stream_response():31 response = await httpcore.request("GET", "http://example.com")3224async 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 == 20034 assert response.body == b"Hello, world!"35 assert response.is_closed3637 body = b''38 async for part in response.stream():39 body += part4041 assert body == b"Hello, world!"42 assert response.body == b"Hello, world!"43 assert response.is_closed444546@pytest.mark.asyncio47async def test_read_streaming_response():48 response = await httpcore.request("GET", "http://example.com", stream=True)4950 assert response.status_code == 20051 assert not hasattr(response, 'body')28 assert not hasattr(response, "body")52 assert not response.is_closed5329 body = await response.read()5530 assert body == b"Hello, world!"57 assert response.body == b"Hello, world!"58 assert response.is_closed313233@pytest.mark.asyncio62async def test_stream_streaming_response():63 response = await httpcore.request("GET", "http://example.com", stream=True)34async def test_stream_request(server):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(41 "POST", "http://127.0.0.1:8000/", body=hello_world()42 )43 assert response.status_code == 20066 assert not hasattr(response, 'body')67 assert not response.is_closed6869 body = b''70 async for part in response.stream():71 body += part7273 assert body == b"Hello, world!"74 assert not hasattr(response, 'body')75 assert response.is_closed767778@pytest.mark.asyncio79async def test_cannot_read_after_stream_consumed():80 response = await httpcore.request("GET", "http://example.com", stream=True)8182 body = b''83 async for part in response.stream():84 body += part8586 with pytest.raises(httpcore.StreamConsumed):87 await response.read()8889@pytest.mark.asyncio90async def test_cannot_read_after_response_closed():91 response = await httpcore.request("GET", "http://example.com", stream=True)9293 await response.close()9495 with pytest.raises(httpcore.ResponseClosed):96 await response.read()
added:tests/test_responses.py+114 added
1import pytest23import httpcore456class 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!"1516 return httpcore.Response(200, body=streaming_body())17 return httpcore.Response(200, body=b"Hello, world!")181920http = MockHTTP()212223@pytest.mark.asyncio24async def test_request():25 response = await http.request("GET", "http://example.com")26 assert response.status_code == 20027 assert response.body == b"Hello, world!"28 assert response.is_closed293031@pytest.mark.asyncio32async def test_read_response():33 response = await http.request("GET", "http://example.com")3435 assert response.status_code == 20036 assert response.body == b"Hello, world!"37 assert response.is_closed3839 body = await response.read()4041 assert body == b"Hello, world!"42 assert response.body == b"Hello, world!"43 assert response.is_closed444546@pytest.mark.asyncio47async def test_stream_response():48 response = await http.request("GET", "http://example.com")4950 assert response.status_code == 20051 assert response.body == b"Hello, world!"52 assert response.is_closed5354 body = b""55 async for part in response.stream():56 body += part5758 assert body == b"Hello, world!"59 assert response.body == b"Hello, world!"60 assert response.is_closed616263@pytest.mark.asyncio64async def test_read_streaming_response():65 response = await http.request("GET", "http://example.com", stream=True)6667 assert response.status_code == 20068 assert not hasattr(response, "body")69 assert not response.is_closed7071 body = await response.read()7273 assert body == b"Hello, world!"74 assert response.body == b"Hello, world!"75 assert response.is_closed767778@pytest.mark.asyncio79async def test_stream_streaming_response():80 response = await http.request("GET", "http://example.com", stream=True)8182 assert response.status_code == 20083 assert not hasattr(response, "body")84 assert not response.is_closed8586 body = b""87 async for part in response.stream():88 body += part8990 assert body == b"Hello, world!"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)9899 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)110111 await response.close()112113 with pytest.raises(httpcore.ResponseClosed):114 await response.read()
modified:README.md+11 added-8 removed
modified:requirements.txt+2 added
1certifi2h1134# Testing5autoflake
3 unmodified lines
9mypy10pytest11pytest-asyncio12pytest-cov13uvicorn