Skip to content

Add support for httpx as backend #1085

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

Open
wants to merge 38 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
38 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
6b73fbb
Merge remote-tracking branch 'origin/master' into httpx
jakkdl Mar 3, 2025
4d4cf32
make no_httpx a separate matrix entry
jakkdl Mar 3, 2025
6daaa79
Merge branch 'master' into httpx
jakkdl Apr 7, 2025
03da7e7
Merge remote-tracking branch 'origin/master' into HEAD
jakkdl May 9, 2025
be976f1
error if unknown http backend
jakkdl May 14, 2025
ae6f1d0
Merge remote-tracking branch 'origin/master' into httpx
jakkdl May 14, 2025
041f7f1
add HttpxStreamingChecksumBody to fix tests. But there's probably a n…
jakkdl May 14, 2025
da5e9fa
fix test_output_compliance fails... as it uses global state 🙃
jakkdl May 14, 2025
e8ba517
stop using include in CI for conditional vars
jakkdl May 14, 2025
7f057b2
quote os value
jakkdl May 14, 2025
109a201
remove HttpxAWSResponse, replace with some logic in AioAWSResponse
jakkdl May 14, 2025
fd8e653
small fixes after review
jakkdl May 14, 2025
b977370
move skip_httpx to tests/conftest
jakkdl May 14, 2025
a4ee8c7
improve exception mapping & retryable exceptions
jakkdl May 15, 2025
e257182
convert iterables to async iterables instead of reading data in send
jakkdl May 19, 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 @@ -40,6 +40,7 @@ jobs:
os:
- ubuntu-24.04
- ubuntu-24.04-arm
no-httpx: [false]
include:
- experimental: false
- experimental: true # no reliable moto release available
Expand All @@ -49,6 +50,12 @@ jobs:
- upload-coverage: true
python-version: 3.11
os: ubuntu-24.04
- no-httpx: true
python-version: 3.13
os: ubuntu-24.04
# this is necessary for matrix.experimental to be defined, otherwise
# CI breaks because continue-on-error is undefined
experimental: false
fail-fast: false
uses: ./.github/workflows/reusable-test.yml
with:
Expand All @@ -57,6 +64,7 @@ jobs:
continue-on-error: ${{ matrix.experimental }}
enable-cache: ${{ github.ref_type == 'tag' && 'false' || 'auto' }}
upload-coverage: ${{ matrix.upload-coverage }}
no-httpx: ${{ matrix.no-httpx }}
secrets:
# yamllint disable-line rule:line-length
codecov-token: ${{ matrix.upload-coverage && secrets.CODECOV_TOKEN || '' }}
Expand Down
15 changes: 14 additions & 1 deletion .github/workflows/reusable-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ on:
required: true
upload-coverage:
type: boolean
no-httpx:
type: boolean
required: true
secrets:
codecov-token:
required: false
Expand All @@ -28,7 +31,9 @@ env:

jobs:
test:
name: Test Python ${{ inputs.python-version }} on ${{ inputs.os }}
name: Test Python ${{ inputs.python-version }} on ${{ inputs.os }}${{
inputs.no-httpx && ' no-httpx' || '' }}

runs-on: ${{ inputs.os }}
continue-on-error: ${{ inputs.continue-on-error }}
env:
Expand All @@ -51,10 +56,18 @@ jobs:
run: |
uv run make pre-commit
- name: Run unittests
if: ${{ ! matrix.no_httpx }}
env:
COLOR: 'yes'
run: |
uv run make mototest
- name: Run unittests without httpx installed
if: ${{ matrix.no_httpx }}
env:
COLOR: 'yes'
HTTP_BACKEND: 'aiohttp'
run: |
uv run --no-group=httpx make mototest
- name: Upload coverage to Codecov
if: ${{ inputs.upload-coverage }}
# yamllint disable-line rule:line-length
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
)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see https://github.com/encode/httpx/blob/80960fa31918d7663c3f4c3ad61661cf0e80628f/httpx/_transports/default.py#L78-L91 for more exception mappings, probably want:

TimeoutException,
 ConnectTimeout, 
ReadTimeout,
 WriteTimeout, 
PoolTimeout, 
NetworkError, 
ConnectError, 
ReadError, 
WriteError, 
ProxyError, 
ProtocolError, 
LocalProtocolError 
and RemoteProtocolError

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would consider that first RuntimeError actually a bug in httpx if you want to report, it really should be throwing a StreamClosed exception as it already has that.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also debating StreamClosed, since you're driving this PR if you could look at that one it would be great. It seems like they're using that for control flow instead of exception handling, no-no-no ;)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would consider that first RuntimeError actually a bug in httpx if you want to report, it really should be throwing a StreamClosed exception as it already has that.

opened encode/httpx#3575

... although maybe StreamClosed is also a bad fit if they're abusing that

Copy link
Contributor Author

@jakkdl jakkdl May 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see https://github.com/encode/httpx/blob/80960fa31918d7663c3f4c3ad61661cf0e80628f/httpx/_transports/default.py#L78-L91 for more exception mappings, probably want:

...

huh, appear the url in the comment is now broken - this is what I think it was linking to: https://www.python-httpx.org/exceptions/#the-exception-hierarchy

Collapsing your list according to inheritance, the list comes out to TimeoutException, ProtocolError, and ConnectError, ReadError and WriteError as the child exceptions of NetworkError (but not NetworkError itself as that would catch CloseError)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also debating StreamClosed, since you're driving this PR if you could look at that one it would be great. It seems like they're using that for control flow instead of exception handling, no-no-no ;)

where are you seeing this?



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 @@ -17,7 +17,12 @@
from aiobotocore.httpchecksum import handle_checksum_body
from aiobotocore.httpsession import AIOHTTPSession
from aiobotocore.parsers import AioResponseParserFactory
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 @@ -50,8 +55,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