Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for httpx as backend #1085

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
1eb6888
Replace aiohttp with httpx
jakkdl Feb 1, 2024
d10761c
WIP of full replacement of aiohttp with httpx
jakkdl Feb 9, 2024
3608872
mostly finished WIP of adding httpx support
jakkdl Feb 19, 2024
757819f
fix various test failures
jakkdl Feb 19, 2024
4327b58
fix more parametrization issues
jakkdl Feb 19, 2024
e123adc
fix typo current_http_stack -> current_http_backend
jakkdl Feb 19, 2024
d029aa4
Add pytest flag for specifying backend when running tests.
jakkdl Feb 20, 2024
8f6bd69
add initial retryable exceptions. _validate_connector_args will now g…
jakkdl Feb 20, 2024
bdc680c
yes
jakkdl Feb 20, 2024
48b7310
append coverage when running tests twice
jakkdl Mar 1, 2024
b19bc09
Merge branch 'master' into httpx
jakkdl Mar 1, 2024
3e38c06
fix normalization of key paths in urls, revert test
jakkdl Apr 3, 2024
3e29d0d
shuffle around code wrt retryable exception to be less confusing
jakkdl Apr 3, 2024
af293b0
Merge remote-tracking branch 'origin/master' into httpx
jakkdl Apr 3, 2024
4482464
Merge remote-tracking branch 'origin/master' into httpx
jakkdl Oct 19, 2024
9dff5be
fix failed merge
jakkdl Oct 19, 2024
746d6b1
ruamel/yaml release pulled, so minor commit to retrigger CI
jakkdl Oct 19, 2024
82f2bc8
pre-merge dir rename
jakkdl Feb 27, 2025
550b660
Merge remote-tracking branch 'origin/master' into httpx
jakkdl Feb 27, 2025
2fd7f29
first fixes after reviews
jakkdl Feb 28, 2025
d1c0d12
fix no-httpx ci run
jakkdl Feb 28, 2025
9462503
add HttpxStreamingBody to reduce test changes
jakkdl Feb 28, 2025
c5d4592
blah
jakkdl Feb 28, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .github/workflows/ci-cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,14 @@ jobs:
COLOR: 'yes'
run: |
uv run make mototest
- name: Run unittests without httpx installed
# run it on same python as codecov
if: matrix.python-version == '3.13'
env:
COLOR: 'yes'
run: |
HTTP_BACKEND='aiohttp' FLAGS='--cov-append' \
uv run --no-group=httpx make mototest
- name: Upload coverage to Codecov
if: ${{ matrix.upload-coverage }}
uses: codecov/[email protected]
Expand Down
5 changes: 3 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Some simple testing tasks (sorry, UNIX only).

# ?= conditional assign, so users can pass options on the CLI instead of manually editing this file
# ?= is conditional assign, so users can pass options on the CLI instead of manually editing this file
HTTP_BACKEND?='all'
FLAGS?=

pre-commit:
Expand All @@ -17,7 +18,7 @@ cov cover coverage: pre-commit
@echo "open file://`pwd`/htmlcov/index.html"

mototest:
python -Wd -X tracemalloc=5 -X faulthandler -m pytest -vv -m "not localonly" -n auto --cov-report term --cov-report html --cov-report xml --cov=aiobotocore --cov=tests --log-cli-level=DEBUG $(FLAGS) aiobotocore tests
python -Wd -X tracemalloc=5 -X faulthandler -m pytest -vv -m "not localonly" -n auto --cov-report term --cov-report html --cov-report xml --cov=aiobotocore --cov=tests --log-cli-level=DEBUG --http-backend=$(HTTP_BACKEND) $(FLAGS) aiobotocore tests

clean:
rm -rf `find . -name __pycache__`
Expand Down
17 changes: 17 additions & 0 deletions aiobotocore/_endpoint_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
import botocore.retryhandler
import wrapt

try:
import httpx
except ImportError:
httpx = None

# Monkey patching: We need to insert the aiohttp exception equivalents
# The only other way to do this would be to have another config file :(
_aiohttp_retryable_exceptions = [
Expand All @@ -14,10 +19,22 @@
asyncio.TimeoutError,
]


botocore.retryhandler.EXCEPTION_MAP['GENERAL_CONNECTION_ERROR'].extend(
_aiohttp_retryable_exceptions
)

if httpx is not None:
# TODO: Wild guesses after looking at https://pydoc.dev/httpx/latest/classIndex.html
# somebody with more network and/or httpx knowledge should revise this list.
_httpx_retryable_exceptions = [
httpx.NetworkError,
httpx.ConnectTimeout,
]
botocore.retryhandler.EXCEPTION_MAP['GENERAL_CONNECTION_ERROR'].extend(
_httpx_retryable_exceptions
)


def _text(s, encoding='utf-8', errors='strict'):
if isinstance(s, bytes):
Expand Down
28 changes: 28 additions & 0 deletions aiobotocore/awsrequest.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,31 @@ async def _text_prop(self):
@property
def text(self):
return self._text_prop()


class HttpxAWSResponse(AWSResponse):
# Unlike AWSResponse, these return awaitables

async def _content_prop(self):
"""Content of the response as bytes."""

if self._content is None:
# NOTE: this will cache the data in self.raw
self._content = await self.raw.aread() or b''

return self._content

@property
def content(self):
return self._content_prop()

async def _text_prop(self):
encoding = botocore.utils.get_encoding_from_headers(self.headers)
if encoding:
return (await self.content).decode(encoding)
else:
return (await self.content).decode('utf-8')

@property
def text(self):
return self._text_prop()
17 changes: 15 additions & 2 deletions aiobotocore/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from botocore.exceptions import ParamValidationError

from aiobotocore.endpoint import DEFAULT_HTTP_SESSION_CLS
from aiobotocore.httpxsession import HttpxSession


class AioConfig(botocore.client.Config):
Expand All @@ -15,7 +16,7 @@ def __init__(
):
super().__init__(**kwargs)

self._validate_connector_args(connector_args)
self._validate_connector_args(connector_args, http_session_cls)
self.connector_args = copy.copy(connector_args)
self.http_session_cls = http_session_cls
if not self.connector_args:
Expand All @@ -35,13 +36,17 @@ def merge(self, other_config):
return AioConfig(self.connector_args, **config_options)

@staticmethod
def _validate_connector_args(connector_args):
def _validate_connector_args(connector_args, http_session_cls):
if connector_args is None:
return

for k, v in connector_args.items():
# verify_ssl is handled by verify parameter to create_client
if k == 'use_dns_cache':
if http_session_cls is HttpxSession:
raise ParamValidationError(
report='Httpx does not support dns caching. https://github.com/encode/httpx/discussions/2211'
)
if not isinstance(v, bool):
raise ParamValidationError(
report=f'{k} value must be a boolean'
Expand All @@ -57,6 +62,10 @@ def _validate_connector_args(connector_args):
report=f'{k} value must be a float/int or None'
)
elif k == 'force_close':
if http_session_cls is HttpxSession:
raise ParamValidationError(
report=f'Httpx backend does not currently support {k}.'
)
if not isinstance(v, bool):
raise ParamValidationError(
report=f'{k} value must be a boolean'
Expand All @@ -72,6 +81,10 @@ def _validate_connector_args(connector_args):
elif k == "resolver":
from aiohttp.abc import AbstractResolver

if http_session_cls is HttpxSession:
raise ParamValidationError(
report=f'Httpx backend does not support {k}.'
)
if not isinstance(v, AbstractResolver):
raise ParamValidationError(
report=f'{k} must be an instance of a AbstractResolver'
Expand Down
14 changes: 11 additions & 3 deletions aiobotocore/endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@

from aiobotocore.httpchecksum import handle_checksum_body
from aiobotocore.httpsession import AIOHTTPSession
from aiobotocore.response import StreamingBody
from aiobotocore.response import HttpxStreamingBody, StreamingBody

try:
import httpx
except ImportError:
httpx = None

DEFAULT_HTTP_SESSION_CLS = AIOHTTPSession

Expand Down Expand Up @@ -49,8 +54,11 @@ async def convert_to_response_dict(http_response, operation_model):
elif operation_model.has_event_stream_output:
response_dict['body'] = http_response.raw
elif operation_model.has_streaming_output:
length = response_dict['headers'].get('content-length')
response_dict['body'] = StreamingBody(http_response.raw, length)
if httpx and isinstance(http_response.raw, httpx.Response):
response_dict['body'] = HttpxStreamingBody(http_response.raw)
else:
length = response_dict['headers'].get('content-length')
response_dict['body'] = StreamingBody(http_response.raw, length)
else:
response_dict['body'] = await http_response.content
return response_dict
Expand Down
Loading
Loading