Stuff
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 d12e5d4 · Browse files · 10 files·+472 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+472 added−0 removed
- tests:+96 added−0 removed
- other:+376 added−0 removed
Provenance
- Commit
30530d4- Tree
88f910c- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
d12e5d4
10 files changed+472 added−0 removed
modified:httpcore/__init__.py+4 added
1+from .api import PoolManager, Response, request2+from .config import PoolLimits, SSLConfig, TimeoutConfig3+from .exceptions import ResponseClosed, StreamConsumed4+5 __version__ = "0.0.1"added:httpcore/api.py+132 added
1+import typing2+from types import TracebackType3+4+from .config import (5+ DEFAULT_POOL_LIMITS,6+ DEFAULT_SSL_CONFIG,7+ DEFAULT_TIMEOUT_CONFIG,8+ PoolLimits,9+ SSLConfig,10+ TimeoutConfig,11+)12+from .exceptions import ResponseClosed, StreamConsumed13+14+15+async 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+ )29+30+31+class 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 = False43+44+ 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!")59+60+ async def close(self) -> None:61+ self.is_closed = True62+63+ async def __aenter__(self) -> "PoolManager":64+ return self65+66+ 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()73+74+75+class 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 = body94+95+ 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.body102+103+ 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()115+116+ 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()121+122+ async def __aenter__(self) -> "Response":123+ return self124+125+ 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()added:httpcore/config.py+54 added
1+import typing2+3+4+class SSLConfig:5+ """6+ SSL Configuration.7+ """8+9+ def __init__(self, *, cert: typing.Optional[str], verify: typing.Union[str, bool]):10+ self.cert = cert11+ self.verify = verify12+13+14+class TimeoutConfig:15+ """16+ Timeout values.17+ """18+19+ def __init__(20+ self,21+ timeout: float = None,22+ *,23+ connect_timeout: float = None,24+ read_timeout: float = None,25+ pool_timeout: float = None26+ ):27+ if timeout is not None:28+ # Specified as a single timeout value29+ assert connect_timeout is None30+ assert read_timeout is None31+ assert pool_timeout is None32+ connect_timeout = timeout33+ read_timeout = timeout34+ pool_timeout = timeout35+36+ self.connect_timeout = connect_timeout37+ self.read_timeout = read_timeout38+ self.pool_timeout = pool_timeout39+40+41+class PoolLimits:42+ """43+ Limits on the number of connections in a connection pool.44+ """45+46+ def __init__(self, *, max_hosts: int, conns_per_host: int, hard_limit: bool):47+ self.max_hosts = max_hosts48+ self.conns_per_host = conns_per_host49+ self.hard_limit = hard_limit50+51+52+DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)53+DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)54+DEFAULT_POOL_LIMITS = PoolLimits(max_hosts=10, conns_per_host=10, hard_limit=False)added:httpcore/exceptions.py+42 added
1+class Timeout(Exception):2+ """3+ A base class for all timeouts.4+ """5+6+7+class ConnectTimeout(Timeout):8+ """9+ Timeout while establishing a connection.10+ """11+12+13+class ReadTimeout(Timeout):14+ """15+ Timeout while reading response data.16+ """17+18+19+class PoolTimeout(Timeout):20+ """21+ Timeout while waiting to acquire a connection from the pool.22+ """23+24+25+class BadResponse(Exception):26+ """27+ A malformed HTTP response.28+ """29+30+31+class StreamConsumed(Exception):32+ """33+ Attempted to read or stream response content, but the content has already34+ been streamed.35+ """36+37+38+class ResponseClosed(Exception):39+ """40+ Attempted to read or stream response content, but the request has been41+ closed without loading the body.42+ """added:scripts/install+24 added
1+#!/bin/sh -e2+3+# Use the Python executable provided from the `-p` option, or a default.4+[[ $1 = "-p" ]] && PYTHON=$2 || PYTHON="python3"5+6+MIN_VERSION="(3, 6)"7+VERSION_OK=`"$PYTHON" -c "import sys; print(sys.version_info[0:2] >= $MIN_VERSION and '1' or '');"`8+9+if [[ -z "$VERSION_OK" ]] ; then10+ PYTHON_VERSION=`"$PYTHON" -c "import sys; print('%s.%s' % sys.version_info[0:2]);"`11+ DISP_MIN_VERSION=`"$PYTHON" -c "print('%s.%s' % $MIN_VERSION)"`12+ echo "ERROR: Python $PYTHON_VERSION detected, but $DISP_MIN_VERSION+ is required."13+ echo "Please upgrade your Python distribution to install Databases."14+ exit 115+fi16+17+REQUIREMENTS="requirements.txt"18+VENV="venv"19+PIP="$VENV/bin/pip"20+21+set -x22+"$PYTHON" -m venv "$VENV"23+"$PIP" install -r "$REQUIREMENTS"24+"$PIP" install -e .added:scripts/lint+15 added
1+#!/bin/sh -e2+3+export PREFIX=""4+if [ -d 'venv' ] ; then5+ export PREFIX="venv/bin/"6+fi7+8+set -x9+10+${PREFIX}autoflake --in-place --recursive httpcore tests11+${PREFIX}black httpcore tests12+${PREFIX}isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --combine-as --line-width 88 --recursive --apply httpcore tests13+${PREFIX}mypy httpcore --ignore-missing-imports --disallow-untyped-defs14+15+scripts/cleanadded:scripts/test+12 added
1+#!/bin/sh -e2+3+export PACKAGE="httpcore"4+export PREFIX=""5+if [ -d 'venv' ] ; then6+ export PREFIX="venv/bin/"7+fi8+9+set -x10+11+PYTHONPATH=. ${PREFIX}pytest --ignore venv --cov tests --cov ${PACKAGE} --cov-report= ${@}12+${PREFIX}coverage reportadded:tests/test_api.py+96 added
1+import pytest2+3+import httpcore4+5+6+@pytest.mark.asyncio7+async def test_request():8+ response = await httpcore.request("GET", "http://example.com")9+ assert response.status_code == 20010+ assert response.body == b"Hello, world!"11+ assert response.is_closed12+13+14+@pytest.mark.asyncio15+async def test_read_response():16+ response = await httpcore.request("GET", "http://example.com")17+18+ assert response.status_code == 20019+ assert response.body == b"Hello, world!"20+ assert response.is_closed21+22+ body = await response.read()23+24+ assert body == b"Hello, world!"25+ assert response.body == b"Hello, world!"26+ assert response.is_closed27+28+29+@pytest.mark.asyncio30+async def test_stream_response():31+ response = await httpcore.request("GET", "http://example.com")32+33+ assert response.status_code == 20034+ assert response.body == b"Hello, world!"35+ assert response.is_closed36+37+ body = b''38+ async for part in response.stream():39+ body += part40+41+ assert body == b"Hello, world!"42+ assert response.body == b"Hello, world!"43+ assert response.is_closed44+45+46+@pytest.mark.asyncio47+async def test_read_streaming_response():48+ response = await httpcore.request("GET", "http://example.com", stream=True)49+50+ assert response.status_code == 20051+ assert not hasattr(response, 'body')52+ assert not response.is_closed53+54+ body = await response.read()55+56+ assert body == b"Hello, world!"57+ assert response.body == b"Hello, world!"58+ assert response.is_closed59+60+61+@pytest.mark.asyncio62+async def test_stream_streaming_response():63+ response = await httpcore.request("GET", "http://example.com", stream=True)64+65+ assert response.status_code == 20066+ assert not hasattr(response, 'body')67+ assert not response.is_closed68+69+ body = b''70+ async for part in response.stream():71+ body += part72+73+ assert body == b"Hello, world!"74+ assert not hasattr(response, 'body')75+ assert response.is_closed76+77+78+@pytest.mark.asyncio79+async def test_cannot_read_after_stream_consumed():80+ response = await httpcore.request("GET", "http://example.com", stream=True)81+82+ body = b''83+ async for part in response.stream():84+ body += part85+86+ with pytest.raises(httpcore.StreamConsumed):87+ await response.read()88+89+@pytest.mark.asyncio90+async def test_cannot_read_after_response_closed():91+ response = await httpcore.request("GET", "http://example.com", stream=True)92+93+ await response.close()94+95+ with pytest.raises(httpcore.ResponseClosed):96+ await response.read()added:README.md+82 added
1+# HTTPCore2+3+I started to dive into implementation and API design here.4+5+I know this isn't what you were suggesting with `requests-core`, but it'd be6+worth you taking a slow look at this and seeing if there's anything that you7+think is a no-go.8+9+`httpcore` provides the same proposed *functionality* as requests-core, but at a slightly10+lower abstraction level.11+12+Rather than returning `Response` models, it returns the minimal possible13+interface. There's no `response.text` or any other cleverness, `response.headers`14+are plain byte-pair lists, rather than a headers datastructure etc...15+16+**The proposal here is that `httpcore` would be a silent-partner dependency of `requests3`,17+taking the place of the existing `urllib3` dependency.**18+19+---20+21+The benefits to my mind of this level of abstraction are that it is as22+agnostic as possible to whatever request/response models are built on top23+of it, and exposes only plain datastructures that reflect the network response.24+25+* An `encode/httpcore` package would be something I'd gladly maintain. The naming26+ makes sense to me, as there's no strictly implied relationship to `requests`,27+ although it would fulfil all the requirements for `requests3` to build on,28+ and would have a strict semver policy.29+* An `encode/httpcore` package is something that would play in well to the30+ collaboratively sponsored OSS story that Encode is pitching. It'd provide what31+ you need for `requests3` without encroaching on the `requests` brand.32+ We'd position it similarly to how `urllib3` is positioned to `requests` now.33+ A focused, low-level networking library, that `requests` then builds the34+ developer-focused API on top of.35+* The current implementation includes all the async API points.36+ The `PoolManger.request()` and `PoolManager.close()` methods are currently37+ stubbed-out. All the remaining implementation hangs off of those two points.38+* Take a quick look over the test cases or the package itself to get a feel39+ for it. It's all type annotated, and should be easy to find your way around.40+* I've not yet added corresponding sync API points to the implementation, but41+ they will come.42+* There's [a chunk of work towards connection pooling here](https://github.com/encode/requests-async/blob/5ec2aa80bd4499997fa744f3be19a0bdeccbaeed/requests_async/connections.py). I've not had enough time to nail it yet, but it's got the broad brush-strokes.43+* We would absolutely want to implement HTTP/2 support.44+* Trio support is something that could *potentially* come later, but it needs to45+ be a secondary consideration.46+* I think all the functionality required is stubbed out in the API, with two exceptions.47+ 1. I've not yet added any proxy configuration API. Haven't looked into that enough48+ yet. 2. I've not yet added any retry configuration API, since I havn't really49+ looked enough into which side of requests vs. urllib3 that sits on, or exactly how50+ urllib3 tackles retries, etc.51+* I'd be planning to prioritize working on this from Mon 15th April. I don't think52+ it'd take too long to get it to a feature complete and API stable state.53+ (With the exception of the later HTTP/2 work, which I can't really assess yet.)54+ I probably don't have any time left before then - need to focus on what I'm55+ delivering to DjangoCon Europe over the rest of this week.56+* To my mind the killer app for `requests3`/`httpcore` is a high-performance57+ proxy server / gateway service in Python. Pitching the growing ASGI ecosystem58+ is an important part of that story.59+* I think there's enough headroom before PyCon to have something ready to pitch by then.60+ I could be involved in sprints remotely if there's areas we still need to fill in,61+ anyplace.62+63+```python64+import httpcore65+66+response = await httpcore.request('GET', 'http://example.com')67+assert response.status_code == 20068+assert response.body == b'Hello, world'69+```70+71+API...72+73+```python74+response = await httpcore.request(method, url, [headers], [body], [stream])75+```76+77+Explicit PoolManager...78+79+```python80+async with httpcore.PoolManager([ssl], [timeout], [limits]) as pool:81+ response = await pool.request(method, url, [headers], [body], [stream])82+```added:requirements.txt+11 added
1+h112+3+# Testing4+autoflake5+black6+codecov7+isort8+mypy9+pytest10+pytest-asyncio11+pytest-cov