Skip to content
Myr

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

4 files+31 added−16 removed

modified:httpx/_content.py+9 added-4 removed
15 unmodified lines
16from ._exceptions import StreamClosed, StreamConsumed17from ._multipart import MultipartStream18from ._transports.base import AsyncByteStream, SyncByteStream19from ._types import RequestContent, RequestData, RequestFiles, ResponseContent20from ._utils import primitive_value_to_str20from ._utils import peek_filelike_length, primitive_value_to_str212223class ByteStream(AsyncByteStream, SyncByteStream):24 def __init__(self, stream: bytes) -> None:
56 unmodified lines
81) -> Tuple[Dict[str, str], Union[SyncByteStream, AsyncByteStream]]:8283 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)8889 elif isinstance(content, Iterable):90 content_length_or_none = peek_filelike_length(content)9192 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: ignore9798 elif isinstance(content, AsyncIterable):99 headers = {"Transfer-Encoding": "chunked"}
108 unmodified lines
modified:httpx/_multipart.py+2 added-3 removed
91 unmodified lines
92 if isinstance(self.file, (str, bytes)):93 return len(headers) + len(to_bytes(self.file))9495 # 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 lines
modified:httpx/_utils.py+8 added-9 removed
340 unmodified lines
341 return mimetypes.guess_type(filename)[0] or "application/octet-stream"342 return None343344345def peek_filelike_length(stream: typing.IO) -> int:345def 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 None366367 return length368369370class Timer:371 async def _get_time(self) -> float:372 library = sniffio.current_async_library()373 if library == "trio":
135 unmodified lines
modified:tests/test_content.py+12 added
47 unmodified lines
48 assert async_content == b"Hello, world!"495051@pytest.mark.asyncio52async 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)5657 content = b"".join([part for part in stream])5859 assert headers == {"Content-Length": "13"}60 assert content == b"Hello, world!"616263@pytest.mark.asyncio64async def test_iterator_content():65 def hello_world():66 yield b"Hello, "67 yield b"world!"
358 unmodified lines