aio-libs/aiohttp · error · TypeError
Unable to read body part as bytes. Use write() to consume.
Error message
Unable to read body part as bytes. Use write() to consume.
What it means
Raised unconditionally by BodyPartReaderPayload.as_bytes(). Like decode(), this method is intentionally forbidden because buffering a streaming body part (which can be gigabytes) into a single bytes object would risk memory exhaustion and can only succeed once. The payload is designed to be consumed via write().
Source
Thrown at aiohttp/multipart.py:662
params["name"] = value.name
if value.filename is not None:
params["filename"] = value.filename
if params:
self.set_content_disposition("attachment", True, **params)
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
raise TypeError("Unable to decode.")
async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes:
"""Raises TypeError as body parts should be consumed via write().
This is intentional: BodyPartReader payloads are designed for streaming
large data (potentially gigabytes) and must be consumed only once via
the write() method to avoid memory exhaustion. They cannot be buffered
in memory for reuse.
"""
raise TypeError("Unable to read body part as bytes. Use write() to consume.")
async def write(self, writer: AbstractStreamWriter) -> None:
field = self._value
while chunk := await field.read_chunk(size=DEFAULT_CHUNK_SIZE):
async for d in field.decode_iter(chunk):
await writer.write(d)
class MultipartReader:
"""Multipart body reader."""
#: Response wrapper, used when multipart readers constructs from response.
response_wrapper_cls = MultipartResponseWrapper
#: Multipart reader class, used to handle multipart/* body parts.
#: None points to type(self)
multipart_reader_cls: type["MultipartReader"] | None = None
#: Body part reader class for non multipart/* content types.
part_reader_cls = BodyPartReaderView on GitHub (pinned to c0ef574e29)
Solutions
- Stream the payload through write() to a destination rather than buffering it.
- If you truly need the bytes in memory, read the underlying BodyPartReader directly: `data = await reader.read()` before wrapping it.
- Guard with isinstance(payload, BodyPartReaderPayload) and skip as_bytes() in generic pipelines.
Example fix
// before body = await payload.as_bytes() // after buf = io.BytesIO() await payload.write(BufferedWriter(buf)) body = buf.getvalue()
Defensive patterns
Strategy: type-guard
Validate before calling
from aiohttp.multipart import BodyPartReaderPayload
if isinstance(payload, BodyPartReaderPayload):
# cannot buffer — stream it instead
raise TypeError('stream this payload via write()') Type guard
from aiohttp.multipart import BodyPartReaderPayload
def can_buffer(p) -> bool:
return not isinstance(p, BodyPartReaderPayload) Try / catch
try:
body = await payload.as_bytes()
except TypeError:
buf = io.BytesIO()
await payload.write(BufferedWriter(buf))
body = buf.getvalue() Prevention
- Check isinstance(payload, BodyPartReaderPayload) before as_bytes().
- Design pipelines around streaming write() rather than buffering.
- If bytes are mandatory, read the BodyPartReader before wrapping it.
When it happens
Trigger: Calling `await payload.as_bytes()` on a BodyPartReaderPayload — e.g. generic code that awaits as_bytes() to inspect/serialize any payload. The method always raises TypeError for this payload type.
Common situations: Logging/inspection middleware that calls as_bytes() on all payloads; request forwarding code that buffers bodies; snapshotting payloads for retry/caching.
Related errors
- Unable to decode.
- Only io.IOBase, multidict and (name, file) pairs allowed, us
- Can not serialize value type: %r headers: %r value: %r
- Could not find starting boundary {self._boundary!r}
- Cannot create payload from %r
AI-assisted analysis of aio-libs/aiohttp@c0ef574e29 (2026-08-04).
Data as JSON: /data/errors/a6e2d66a0a2f299f.json.
Report an issue: GitHub.