Support async file objects in `content=` and `files=`
Summary
This is my third attempt at this. This PR resolves #597 and implements chunked upload for anyio.open_file, trio.open_file and aiofiles.open when used as content= parameter for post and put request and implements support for multipart file upload for the same libraries. Previous attempts were https://github.com/encode/httpx/pull/3339 and https://github.com/encode/httpx/pull/3698 against encode/httpx, both went stale while the library was unmaintained. Most of the code is reworked from https://github.com/encode/httpx/pull/3698, with the review comments left on https://github.com/encode/httpx/pull/3339 applied.
Currently content= with an async file iterates it a line at a time instead of reading in chunks, so a file without newlines gets buffered whole, and files= with an async file loops forever on both clients, since MultipartStream.__aiter__ just delegates to the sync iter_chunks() and read() returns a coroutine, which is always truthy.
changes
_types.AsyncReadableFileprotocol was added, and_types.FileContentwas extended to include it_utils.is_async_readable_filetype predicate function was added to detect and perform type narrowing for trio/anyio/aiofiles async files_utils.aiter_file_chunkswas added to read an async file in chunks from its current position, shared bycontent=and multipart_utils.peek_async_filelike_lengthwas added, async wrappers expose a syncfileno()so the fd can be stat'ed, there's notell()/seek()fallback like the sync version because those would need awaiting, and it only returns a size for regular files so pipes fall back to chunked encoding_content.AsyncIteratorByteStreamupdated to useawait read()for async files instead of looping over linescontent=with an async file is sent withTransfer-Encoding: chunkedfrom the file's current position, matching how sync files respect the cursor since #1214_multipart.FileFieldupdated witharender_data, which rewinds the file like the sync path, andget_length/render_datamade async-aware, syncClientnow raisesTypeErrorinstead of looping_multipart.MultipartStreamupdated withaiter_chunks, and__aiter__updated to use it, both wrapped incontextlib.aclosing- async files must be opened in binary mode, same as sync ones
- tests added to
test_content.py,test_multipart.pyandtest_utils.py, including a realtrio.open_file()upload and a multipart upload resent on a 307 redirect, docs and changelog updated
perf
content=over 4 MiB with 64-byte lines: 9.18 ms -> 0.33 ms (encoding path, in-memory file, so no disk I/O in the number)- the type predicate runs at most once per file field or
content=stream, never per chunk
Checklist
- I understand that this PR may be closed in case there was no previous discussion. (This doesn't apply to typos!)
- I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
- I've updated the documentation accordingly.