Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python
13.6 KB
Raw Blame
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 57fa44b..143799e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
 ### Added
 
 * Expose `FunctionAuth` from the public API. (#3699)
+* Add `Response.iter_multipart()` and `Response.aiter_multipart()` for parsing `multipart/*` response bodies.
 
 ## 0.28.1 (6th December, 2024)
 
diff --git a/docs/api.md b/docs/api.md
index f1bd50c..69df04a 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -77,6 +77,7 @@
 * `def .iter_bytes([chunk_size])` - **bytes iterator**
 * `def .iter_text([chunk_size])` - **text iterator**
 * `def .iter_lines()` - **text iterator**
+* `def .iter_multipart()` - **MultipartPart iterator**
 * `def .close()` - **None**
 * `def .next()` - **Response**
 * `def .aread()` - **bytes**
@@ -84,6 +85,7 @@
 * `def .aiter_bytes([chunk_size])` - **async bytes iterator**
 * `def .aiter_text([chunk_size])` - **async text iterator**
 * `def .aiter_lines()` - **async text iterator**
+* `def .aiter_multipart()` - **async MultipartPart iterator**
 * `def .aclose()` - **None**
 * `def .anext()` - **Response**
 
diff --git a/httpx/__init__.py b/httpx/__init__.py
index 6322504..0255056 100644
--- a/httpx/__init__.py
+++ b/httpx/__init__.py
@@ -62,6 +62,7 @@ __all__ = [
     "LocalProtocolError",
     "main",
     "MockTransport",
+    "MultipartPart",
     "NetRCAuth",
     "NetworkError",
     "options",
diff --git a/httpx/_models.py b/httpx/_models.py
index 2cc8632..cd70a88 100644
--- a/httpx/_models.py
+++ b/httpx/_models.py
@@ -30,7 +30,12 @@ from ._exceptions import (
     StreamConsumed,
     request_context,
 )
-from ._multipart import get_multipart_boundary_from_content_type
+from ._multipart import (
+    MultipartParser,
+    MultipartPart,
+    get_multipart_boundary_from_content_type,
+    parse_response_multipart_boundary,
+)
 from ._status_codes import codes
 from ._types import (
     AsyncByteStream,
@@ -48,7 +53,7 @@ from ._types import (
 from ._urls import URL
 from ._utils import to_bytes_or_str, to_str
 
-__all__ = ["Cookies", "Headers", "Request", "Response"]
+__all__ = ["Cookies", "Headers", "MultipartPart", "Request", "Response"]
 
 SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}
 
@@ -932,6 +937,27 @@ class Response:
             for line in decoder.flush():
                 yield line
 
+    def iter_multipart(self) -> typing.Iterator[MultipartPart]:
+        """
+        An iterator over parts in a `multipart/*` response body.
+        """
+        with request_context(request=self._request):
+            boundary = parse_response_multipart_boundary(
+                self.headers.get("Content-Type")
+            )
+            parser = MultipartParser(boundary)
+            if hasattr(self, "_content"):
+                for part in parser.feed(self._content):
+                    yield part
+                for part in parser.finish():
+                    yield part
+            else:
+                for chunk in self.iter_bytes():
+                    for part in parser.feed(chunk):
+                        yield part
+                for part in parser.finish():
+                    yield part
+
     def iter_raw(self, chunk_size: int | None = None) -> typing.Iterator[bytes]:
         """
         A byte-iterator over the raw response content.
@@ -1034,6 +1060,27 @@ class Response:
             for line in decoder.flush():
                 yield line
 
+    async def aiter_multipart(self) -> typing.AsyncIterator[MultipartPart]:
+        """
+        An async iterator over parts in a `multipart/*` response body.
+        """
+        with request_context(request=self._request):
+            boundary = parse_response_multipart_boundary(
+                self.headers.get("Content-Type")
+            )
+            parser = MultipartParser(boundary)
+            if hasattr(self, "_content"):
+                for part in parser.feed(self._content):
+                    yield part
+                for part in parser.finish():
+                    yield part
+            else:
+                async for chunk in self.aiter_bytes():
+                    for part in parser.feed(chunk):
+                        yield part
+                for part in parser.finish():
+                    yield part
+
     async def aiter_raw(
         self, chunk_size: int | None = None
     ) -> typing.AsyncIterator[bytes]:
diff --git a/httpx/_multipart.py b/httpx/_multipart.py
index b4761af..c4c2779 100644
--- a/httpx/_multipart.py
+++ b/httpx/_multipart.py
@@ -7,6 +7,7 @@ import re
 import typing
 from pathlib import Path
 
+from ._exceptions import DecodingError
 from ._types import (
     AsyncByteStream,
     FileContent,
@@ -298,3 +299,267 @@ class MultipartStream(SyncByteStream, AsyncByteStream):
     async def __aiter__(self) -> typing.AsyncIterator[bytes]:
         for chunk in self.iter_chunks():
             yield chunk
+
+
+# Response multipart parsing.
+#
+# Delimiter lines follow RFC 2046: `--boundary` / `--boundary--` with optional
+# trailing SP/HTAB. Line breaks may be LF, CR, or CRLF (including CRLF split
+# across chunks).
+
+
+if typing.TYPE_CHECKING:  # pragma: no cover
+    from ._models import Headers
+
+
+class MultipartPart:
+    """
+    A single part from a `multipart/*` response body.
+    """
+
+    def __init__(self, headers: Headers, content: bytes) -> None:
+        self.headers = headers
+        self.content = content
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, MultipartPart):
+            return NotImplemented
+        return self.headers == other.headers and self.content == other.content
+
+    def __repr__(self) -> str:
+        return f"MultipartPart(headers={self.headers!r}, content={self.content!r})"
+
+
+def parse_response_multipart_boundary(content_type: str | None) -> bytes:
+    """
+    Return the multipart boundary from a `Content-Type` header.
+
+    Raises `DecodingError` if the header is not a valid `multipart/*` type
+    with a usable boundary parameter.
+    """
+    if content_type is None:
+        raise DecodingError(
+            "Cannot parse multipart response: missing Content-Type header"
+        )
+    if "\r" in content_type or "\n" in content_type:
+        raise DecodingError("Invalid multipart boundary")
+
+    media_type, params = _split_media_type_and_params(content_type)
+    media_type = media_type.strip(" \t")
+    media_lower = media_type.lower()
+    if not media_lower.startswith("multipart/"):
+        raise DecodingError(
+            "Cannot parse multipart response: Content-Type is not multipart"
+        )
+    subtype = media_lower[len("multipart/") :]
+    if not subtype:
+        raise DecodingError("Invalid multipart Content-Type: empty subtype")
+
+    boundary_value: str | None = None
+    for name, value in params:
+        if name.lower() == "boundary":
+            boundary_value = value  # last wins
+
+    if boundary_value is None:
+        raise DecodingError("Invalid multipart boundary")
+
+    return _validate_multipart_boundary(boundary_value)
+
+
+def _split_media_type_and_params(value: str) -> tuple[str, list[tuple[str, str]]]:
+    parts: list[str] = []
+    current: list[str] = []
+    in_quotes = False
+    for char in value:
+        if char == '"':
+            in_quotes = not in_quotes
+            current.append(char)
+        elif char == ";" and not in_quotes:
+            parts.append("".join(current))
+            current = []
+        else:
+            current.append(char)
+    parts.append("".join(current))
+
+    media_type = parts[0] if parts else ""
+    params: list[tuple[str, str]] = []
+    for item in parts[1:]:
+        if "=" not in item:
+            continue
+        name, raw_value = item.split("=", 1)
+        params.append((name.strip(" \t"), raw_value))
+    return media_type, params
+
+
+def _validate_multipart_boundary(value: str) -> bytes:
+    value = value.strip(" \t")
+    if value.startswith('"'):
+        if len(value) < 2 or not value.endswith('"'):
+            raise DecodingError("Invalid multipart boundary")
+        value = value[1:-1]
+
+    if not value:
+        raise DecodingError("Invalid multipart boundary")
+    if value.startswith("="):
+        raise DecodingError("Invalid multipart boundary")
+    if "\x00" in value:
+        raise DecodingError("Invalid multipart boundary")
+    try:
+        return value.encode("ascii")
+    except UnicodeEncodeError:
+        raise DecodingError("Invalid multipart boundary") from None
+
+
+def _delimiter_kind(line: bytes, boundary: bytes) -> str | None:
+    core = line.rstrip(b" \t")
+    prefix = b"--" + boundary
+    if core == prefix:
+        return "open"
+    if core == prefix + b"--":
+        return "close"
+    return None
+
+
+def _parse_part_headers(lines: list[bytes]) -> Headers:
+    from ._models import Headers
+
+    pairs: list[tuple[bytes, bytes]] = []
+    for line in lines:
+        if line.startswith((b" ", b"\t")):
+            if not pairs or line.strip(b" \t") == b"":
+                raise DecodingError("Malformed multipart headers")
+            prev_name, prev_value = pairs[-1]
+            pairs[-1] = (prev_name, prev_value + line)
+            continue
+        if b":" not in line:
+            raise DecodingError("Malformed multipart headers")
+        name, value = line.split(b":", 1)
+        if name == b"":
+            raise DecodingError("Malformed multipart headers")
+        pairs.append((name, value))
+
+    items = [(name, value.strip(b" \t")) for name, value in pairs]
+    return Headers(items, encoding="iso-8859-1")
+
+
+class MultipartParser:
+    """
+    Incrementally parse a `multipart/*` body into `MultipartPart` values.
+    """
+
+    def __init__(self, boundary: bytes) -> None:
+        self.boundary = boundary
+        self._buf = bytearray()
+        self._state = "preamble"
+        self._first_line = True
+        self._header_lines: list[bytes] = []
+        self._headers: Headers | None = None
+        self._body: list[bytes] = []
+        self._pending_term = b""
+
+    def feed(self, data: bytes) -> list[MultipartPart]:
+        if self._state == "epilogue" or not data:
+            return []
+        self._buf.extend(data)
+        return self._process(final=False)
+
+    def finish(self) -> list[MultipartPart]:
+        parts = self._process(final=True)
+        if self._state != "epilogue":
+            raise DecodingError("Malformed multipart framing")
+        return parts
+
+    def _process(self, final: bool) -> list[MultipartPart]:
+        parts: list[MultipartPart] = []
+        for line, term in self._pop_lines(final):
+            part = self._handle_line(line, term)
+            if part is not None:
+                parts.append(part)
+        return parts
+
+    def _pop_lines(self, final: bool) -> list[tuple[bytes, bytes]]:
+        lines: list[tuple[bytes, bytes]] = []
+        buf = self._buf
+        start = 0
+        i = 0
+        n = len(buf)
+        while i < n:
+            byte = buf[i]
+            if byte == 10:  # LF
+                lines.append((bytes(buf[start:i]), b"\n"))
+                i += 1
+                start = i
+            elif byte == 13:  # CR
+                if i + 1 < n and buf[i + 1] == 10:
+                    lines.append((bytes(buf[start:i]), b"\r\n"))
+                    i += 2
+                    start = i
+                elif i + 1 < n:
+                    lines.append((bytes(buf[start:i]), b"\r"))
+                    i += 1
+                    start = i
+                elif final:
+                    lines.append((bytes(buf[start:i]), b"\r"))
+                    i += 1
+                    start = i
+                else:
+                    break
+            else:
+                i += 1
+        if final and start < n:
+            lines.append((bytes(buf[start:]), b""))
+            start = n
+        del buf[:start]
+        return lines
+
+    def _handle_line(self, line: bytes, term: bytes) -> MultipartPart | None:
+        if self._state == "epilogue":
+            return None
+
+        prefix = b"--" + self.boundary
+        if self._first_line:
+            self._first_line = False
+            if line.startswith(prefix) and _delimiter_kind(line, self.boundary) is None:
+                raise DecodingError("Malformed multipart framing")
+
+        kind = _delimiter_kind(line, self.boundary)
+
+        if self._state == "preamble":
+            if kind == "close":
+                self._state = "epilogue"
+            elif kind == "open":
+                self._state = "headers"
+                self._header_lines = []
+            return None
+
+        if self._state == "headers":
+            if kind is not None:
+                raise DecodingError("Malformed multipart headers")
+            if line == b"":
+                self._headers = _parse_part_headers(self._header_lines)
+                self._state = "body"
+                self._body = []
+                self._pending_term = b""
+                return None
+            self._header_lines.append(line)
+            return None
+
+        # body
+        if kind is not None:
+            content = b"".join(self._body)
+            assert self._headers is not None
+            part = MultipartPart(headers=self._headers, content=content)
+            self._headers = None
+            self._header_lines = []
+            self._body = []
+            self._pending_term = b""
+            if kind == "close":
+                self._state = "epilogue"
+            else:
+                self._state = "headers"
+            return part
+
+        self._body.append(self._pending_term)
+        self._body.append(line)
+        self._pending_term = term
+        return None