Skip to content
Myr

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

10 files+472 added−0 removed

modified:httpcore/__init__.py+4 added
1from .api import PoolManager, Response, request2from .config import PoolLimits, SSLConfig, TimeoutConfig3from .exceptions import ResponseClosed, StreamConsumed45__version__ = "0.0.1"
added:httpcore/api.py+132 added
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()
added:httpcore/config.py+54 added
1import typing234class SSLConfig:5 """6 SSL Configuration.7 """89 def __init__(self, *, cert: typing.Optional[str], verify: typing.Union[str, bool]):10 self.cert = cert11 self.verify = verify121314class TimeoutConfig:15 """16 Timeout values.17 """1819 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 = timeout3536 self.connect_timeout = connect_timeout37 self.read_timeout = read_timeout38 self.pool_timeout = pool_timeout394041class PoolLimits:42 """43 Limits on the number of connections in a connection pool.44 """4546 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_limit505152DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)53DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)54DEFAULT_POOL_LIMITS = PoolLimits(max_hosts=10, conns_per_host=10, hard_limit=False)
added:httpcore/exceptions.py+42 added
1class Timeout(Exception):2 """3 A base class for all timeouts.4 """567class ConnectTimeout(Timeout):8 """9 Timeout while establishing a connection.10 """111213class ReadTimeout(Timeout):14 """15 Timeout while reading response data.16 """171819class PoolTimeout(Timeout):20 """21 Timeout while waiting to acquire a connection from the pool.22 """232425class BadResponse(Exception):26 """27 A malformed HTTP response.28 """293031class StreamConsumed(Exception):32 """33 Attempted to read or stream response content, but the content has already34 been streamed.35 """363738class 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 -e23# Use the Python executable provided from the `-p` option, or a default.4[[ $1 = "-p" ]] && PYTHON=$2 || PYTHON="python3"56MIN_VERSION="(3, 6)"7VERSION_OK=`"$PYTHON" -c "import sys; print(sys.version_info[0:2] >= $MIN_VERSION and '1' or '');"`89if [[ -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 115fi1617REQUIREMENTS="requirements.txt"18VENV="venv"19PIP="$VENV/bin/pip"2021set -x22"$PYTHON" -m venv "$VENV"23"$PIP" install -r "$REQUIREMENTS"24"$PIP" install -e .
added:scripts/lint+15 added
1#!/bin/sh -e23export PREFIX=""4if [ -d 'venv' ] ; then5 export PREFIX="venv/bin/"6fi78set -x910${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-defs1415scripts/clean
added:scripts/test+12 added
1#!/bin/sh -e23export PACKAGE="httpcore"4export PREFIX=""5if [ -d 'venv' ] ; then6 export PREFIX="venv/bin/"7fi89set -x1011PYTHONPATH=. ${PREFIX}pytest --ignore venv --cov tests --cov ${PACKAGE} --cov-report= ${@}12${PREFIX}coverage report
added:tests/test_api.py+96 added
1import pytest23import httpcore456@pytest.mark.asyncio7async 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_closed121314@pytest.mark.asyncio15async def test_read_response():16 response = await httpcore.request("GET", "http://example.com")1718 assert response.status_code == 20019 assert response.body == b"Hello, world!"20 assert response.is_closed2122 body = await response.read()2324 assert body == b"Hello, world!"25 assert response.body == b"Hello, world!"26 assert response.is_closed272829@pytest.mark.asyncio30async def test_stream_response():31 response = await httpcore.request("GET", "http://example.com")3233 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')52 assert not response.is_closed5354 body = await response.read()5556 assert body == b"Hello, world!"57 assert response.body == b"Hello, world!"58 assert response.is_closed596061@pytest.mark.asyncio62async def test_stream_streaming_response():63 response = await httpcore.request("GET", "http://example.com", stream=True)6465 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:README.md+82 added
1# HTTPCore23I started to dive into implementation and API design here.45I know this isn't what you were suggesting with `requests-core`, but it'd be6worth you taking a slow look at this and seeing if there's anything that you7think is a no-go.89`httpcore` provides the same proposed *functionality* as requests-core, but at a slightly10lower abstraction level.1112Rather than returning `Response` models, it returns the minimal possible13interface. There's no `response.text` or any other cleverness, `response.headers`14are plain byte-pair lists, rather than a headers datastructure etc...1516**The proposal here is that `httpcore` would be a silent-partner dependency of `requests3`,17taking the place of the existing `urllib3` dependency.**1819---2021The benefits to my mind of this level of abstraction are that it is as22agnostic as possible to whatever request/response models are built on top23of it, and exposes only plain datastructures that reflect the network response.2425* 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.6263```python64import httpcore6566response = await httpcore.request('GET', 'http://example.com')67assert response.status_code == 20068assert response.body == b'Hello, world'69```7071API...7273```python74response = await httpcore.request(method, url, [headers], [body], [stream])75```7677Explicit PoolManager...7879```python80async with httpcore.PoolManager([ssl], [timeout], [limits]) as pool:81 response = await pool.request(method, url, [headers], [body], [stream])82```
added:requirements.txt+11 added
1h1123# Testing4autoflake5black6codecov7isort8mypy9pytest10pytest-asyncio11pytest-cov