Prefer `Content-Length` over `Transfer-Encoding: chunked` for `content=<file-like>` cases. (#1619)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add failing test case for 'content=io.BytesIO(...)' * Refactor peek_filelike_length to return an Optional[int] * Peek filelength on file-like objects when rendering 'content=...'
authored by Tom Christie · committed by GitHub · parent 54f4194 · Browse files · 4 files·+31 added−16 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+31 added−16 removed
- tests:+12 added−0 removed
- other:+19 added−16 removed
Provenance
- Commit
2129a97- Tree
cc5277d- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
54f4194
4 files changed+31 added−16 removed
modified:httpx/_content.py+9 added-4 removed
15 unmodified lines16 from ._exceptions import StreamClosed, StreamConsumed17 from ._multipart import MultipartStream18 from ._transports.base import AsyncByteStream, SyncByteStream19 from ._types import RequestContent, RequestData, RequestFiles, ResponseContent20-from ._utils import primitive_value_to_str20+from ._utils import peek_filelike_length, primitive_value_to_str21 22 23 class ByteStream(AsyncByteStream, SyncByteStream):24 def __init__(self, stream: bytes) -> None:56 unmodified lines81 ) -> Tuple[Dict[str, str], Union[SyncByteStream, AsyncByteStream]]:82 83 if isinstance(content, (bytes, str)):84 body = content.encode("utf-8") if isinstance(content, str) else content85- content_length = str(len(body))86- headers = {"Content-Length": content_length} if body else {}85+ content_length = len(body)86+ headers = {"Content-Length": str(content_length)} if body else {}87 return headers, ByteStream(body)88 89 elif isinstance(content, Iterable):90+ content_length_or_none = peek_filelike_length(content)91+92+ if content_length_or_none is None:90- headers = {"Transfer-Encoding": "chunked"}93+ headers = {"Transfer-Encoding": "chunked"}94+ else:95+ headers = {"Content-Length": str(content_length_or_none)}96 return headers, IteratorByteStream(content) # type: ignore97 98 elif isinstance(content, AsyncIterable):99 headers = {"Transfer-Encoding": "chunked"}108 unmodified linesmodified:httpx/_multipart.py+2 added-3 removed
91 unmodified lines92 if isinstance(self.file, (str, bytes)):93 return len(headers) + len(to_bytes(self.file))94 95 # Let's do our best not to read `file` into memory.96- try:97- file_length = peek_filelike_length(self.file)98- except OSError:96+ file_length = peek_filelike_length(self.file)97+ if file_length is None:98 # As a last resort, read file and cache contents for later.99 assert not hasattr(self, "_data")100 self._data = to_bytes(self.file.read())101 file_length = len(self._data)104 unmodified linesmodified:httpx/_utils.py+8 added-9 removed
340 unmodified lines341 return mimetypes.guess_type(filename)[0] or "application/octet-stream"342 return None343 344 345-def peek_filelike_length(stream: typing.IO) -> int:345+def peek_filelike_length(stream: typing.Any) -> typing.Optional[int]:346 """347 Given a file-like stream object, return its length in number of bytes348 without reading it into memory.349 """350 try:351 # Is it an actual file?352 fd = stream.fileno()353- except OSError:353+ # Yup, seems to be an actual file.354+ length = os.fstat(fd).st_size355+ except (AttributeError, OSError):356 # No... Maybe it's something that supports random access, like `io.BytesIO`?357 try:358 # Assuming so, go to end of stream to figure out its length,359 # then put it back in place.360 offset = stream.tell()361 length = stream.seek(0, os.SEEK_END)362 stream.seek(offset)361- except OSError:363+ except (AttributeError, OSError):364 # Not even that? Sorry, we're doomed...363- raise364- else:365- return length366- else:367- # Yup, seems to be an actual file.368- return os.fstat(fd).st_size365+ return None366 367+ return length368 369+370 class Timer:371 async def _get_time(self) -> float:372 library = sniffio.current_async_library()373 if library == "trio":135 unmodified linesmodified:tests/test_content.py+12 added
47 unmodified lines48 assert async_content == b"Hello, world!"49 50 51 @pytest.mark.asyncio52+async def test_bytesio_content():53+ headers, stream = encode_request(content=io.BytesIO(b"Hello, world!"))54+ assert isinstance(stream, typing.Iterable)55+ assert not isinstance(stream, typing.AsyncIterable)56+57+ content = b"".join([part for part in stream])58+59+ assert headers == {"Content-Length": "13"}60+ assert content == b"Hello, world!"61+62+63+@pytest.mark.asyncio64 async def test_iterator_content():65 def hello_world():66 yield b"Hello, "67 yield b"world!"358 unmodified lines