diff --git a/Cargo.lock b/Cargo.lock
index 1c653627..3586d7e4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2652,6 +2652,7 @@ dependencies = [
"http-body",
"http-body-util",
"indexmap",
+ "memchr",
"mimalloc",
"pingora-runtime",
"pyo3",
diff --git a/Cargo.toml b/Cargo.toml
index ea83fda9..3dca298c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -44,6 +44,7 @@ serde_json = "1"
serde_urlencoded = "0.7.1"
indexmap = { version = "2.13.0", features = ["serde"] }
bytes = "1.12.1"
+memchr = "2.8"
http = "1.4.2"
http-body = "1.1.0"
http-body-util = "0.1.4"
diff --git a/RELEASE.md b/RELEASE.md
index 8604b96b..b6c86685 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -5,6 +5,8 @@
- Unknown keyword arguments now raise `TypeError` when calling async or blocking client constructors, HTTP or WebSocket request methods and functions, `Http1Options`, `Http2Options`, `TlsOptions`, or `Proxy` factories. These arguments were previously ignored.
- Set client-only options such as `connect_timeout` and `proxies` on `Client`; passing them to a request now raises `TypeError`. Use `proxy` to select a proxy for one request.
- Async request calls check keyword names before returning a coroutine. Values for supported request keywords are still converted on first `await` or entry with `async with`.
+- Header names and values, `Message.ping`/`pong` and `TlsInfo.peer_certificate()` return `bytes` again instead of `memoryview`. `Response.bytes()`, stream data frames and `Message.data`/`binary` return the new immutable `wreq.Bytes`, which shares data without copying and compares and hashes like `bytes`. Tell stream frames apart with `isinstance(chunk, HeaderMap)` rather than `isinstance(chunk, memoryview)`, and use `memoryview(data)` for `memoryview` attributes such as `.obj`, `.cast()` or `.tolist()`. `bytes` values have no `.tobytes()` or `.release()`; on `wreq.Bytes`, `release()` and `with` emit `DeprecationWarning`. APIs that accept only `bytes`, `bytearray` or `memoryview` by type, such as asyncio `StreamWriter.write` and transports or `orjson.loads`, reject `wreq.Bytes`; pass `memoryview(data)`, which does not copy.
+- `memoryview` and `wreq.Bytes` values are now accepted wherever `bytes` is, and are sent as raw bytes. `body=` and `Message.from_binary()` previously JSON-encoded a `memoryview` as an array of integers.
## [0.11.0](https://github.com/0x676e67/wreq-python/compare/v0.10.2..v0.11.0) - 2026-04-13
diff --git a/docs/source/api/wreq.md b/docs/source/api/wreq.md
index 3d157f79..d3befe99 100644
--- a/docs/source/api/wreq.md
+++ b/docs/source/api/wreq.md
@@ -59,6 +59,12 @@ The main `wreq` module contains core classes and types used throughout the libra
options:
show_root_heading: true
+## Binary Data
+
+::: wreq.Bytes
+ options:
+ show_root_heading: true
+
## Network Types
::: wreq.SocketAddr
diff --git a/docs/source/getting-started/introduction.md b/docs/source/getting-started/introduction.md
index ad2d66f0..ccb2dad5 100644
--- a/docs/source/getting-started/introduction.md
+++ b/docs/source/getting-started/introduction.md
@@ -52,11 +52,14 @@ connections, and use context managers to close resources when you're done.
- **Streaming and buffers**
- Stream request and response bodies, or read a complete body. Rust-backed
- binary outputs are read-only `memoryview` objects. Convert to `bytes` when
- an API requires that type; the conversion copies the data.
-
- [Advanced features](../guide/advanced.md)
+ Stream request and response bodies, or read a complete body. Bodies and
+ stream data are zero-copy `wreq.Bytes` objects, and short values such as
+ headers are `bytes`. Use `data.tobytes()` when an API requires `bytes`; the
+ conversion copies the data.
+
+ [Streaming responses](../guide/basic.md#streaming-responses) ·
+ [Uploads](../guide/advanced.md#streaming-request-bodies) ·
+ [Binary data](quickstart.md#binary-data)
- **Runtime configuration**
diff --git a/docs/source/getting-started/quickstart.md b/docs/source/getting-started/quickstart.md
index 3e26598a..99a840b4 100644
--- a/docs/source/getting-started/quickstart.md
+++ b/docs/source/getting-started/quickstart.md
@@ -108,32 +108,36 @@ Finish each read before starting another. For large bodies, see
### Binary data
-`bytes()` returns a read-only `memoryview` backed by Rust-owned data. Returning
-the view is zero-copy; collecting a complete response can still allocate memory
-to join body chunks.
+`bytes()` returns an immutable `wreq.Bytes` backed by Rust-owned data. Returning
+it is zero-copy; collecting a complete response can still allocate memory to
+join body chunks.
```python
import hashlib
async with client.get("https://httpbin.org/bytes/16") as response:
- view = await response.bytes()
+ data = await response.bytes()
-print(view.readonly) # True
-print(hashlib.sha256(view).hexdigest())
+print(len(data), data[:4])
+print(hashlib.sha256(data).hexdigest())
```
-The view remains valid after the response closes. Use it directly with APIs
-that accept buffers, such as `file.write(view)` or `hashlib.sha256(view)`.
-For text, use `str(view, "utf-8")`; memoryviews have no `.decode()` method.
-
-Use `bytes(view)` or `view.tobytes()` when an API needs a `bytes` object. Both
-copy the data. This includes passing a view back to wreq's binary inputs such
-as `body`, `Part`, `Message` constructors or `CertStore`. You can release your
-reference early with `view.release()`; other views and slices stay valid.
-
-The blocking API returns the same type. Stream data frames, binary WebSocket
-fields, header names and values, and peer certificates also use read-only
-memoryviews that retain their backing data.
+The data remains valid after the response closes. Use it directly with APIs
+that accept buffers, such as `file.write(data)` or `hashlib.sha256(data)`. It
+compares and hashes like `bytes`, and provides read-only `bytes` methods such as
+`decode()`, `find()`, `count()` and `startswith()`, plus zero-copy slicing.
+Passing it back to wreq, for example as a request `body` or to
+`Message.from_binary`, does not copy it.
+
+Use `data.tobytes()` when an API needs a `bytes` object, such as `json.loads`
+or code that checks `isinstance(x, bytes)`; it copies the data. APIs that accept
+only `bytes`, `bytearray` or `memoryview` by type, such as asyncio transports
+and `orjson.loads`, take `memoryview(data)` without copying.
+
+The blocking API returns the same type, and so do stream data frames and the
+`data` and `binary` fields of WebSocket messages. Short values are plain
+`bytes`: header names and values, WebSocket ping and pong payloads, and peer
+certificates.
## Set headers
diff --git a/docs/source/guide/advanced.md b/docs/source/guide/advanced.md
index c1a815c2..57c2fad0 100644
--- a/docs/source/guide/advanced.md
+++ b/docs/source/guide/advanced.md
@@ -1,12 +1,13 @@
# Advanced features
Use streaming uploads for data produced incrementally, and multipart forms for
-named fields and files. Response streaming is covered in [basic usage](basic.md).
+named fields and files. Response streaming is covered in
+[basic usage](basic.md#streaming-responses).
## Streaming request bodies
Pass a synchronous iterator or an async generator to `body`. Each item must
-be a supported body chunk, such as `bytes` or `str`:
+be `str` or bytes-like data, such as `bytes` or `wreq.Bytes`:
```python
import asyncio
diff --git a/docs/source/guide/basic.md b/docs/source/guide/basic.md
index cf03e13b..d357c50b 100644
--- a/docs/source/guide/basic.md
+++ b/docs/source/guide/basic.md
@@ -82,8 +82,9 @@ keywords are converted when the coroutine is first awaited or entered with
## Request bodies
Use `json` for JSON, `form` for URL-encoded fields, and `body` for raw text or
-bytes. `json` and `form` set their content type automatically. Set it explicitly
-for a raw body when the server needs it. Choose one body argument per request.
+bytes-like data (`bytes`, `bytearray`, `memoryview` or `wreq.Bytes`). `json` and
+`form` set their content type automatically. Set it explicitly for a raw body
+when the server needs it. Choose one body argument per request.
```python
async with client.post(
@@ -117,18 +118,17 @@ from wreq.header import HeaderMap
headers = HeaderMap({"Accept": "application/json"})
headers.append("Accept", "text/html")
-print([str(value, "ascii") for value in headers.get_all("accept")])
+print([value.decode("ascii") for value in headers.get_all("accept")])
async with client.get("https://httpbin.org/headers", headers=headers) as response:
content_type = response.headers.get("content-type")
if content_type is not None:
- print(str(content_type, "ascii"))
+ print(content_type.decode("ascii"))
print(await response.json())
```
Header names are case insensitive. Header names and values returned by
-`HeaderMap` are read-only memoryviews; `str(view, encoding)` decodes them
-without an intermediate `bytes` copy.
+`HeaderMap` are `bytes`.
## Authentication
@@ -209,10 +209,10 @@ another. `stream()` only accepts an unread body and transfers it to a streamer;
after that, use the streamer to read it. Reading a released body or starting an
overlapping read raises `RuntimeError`.
-`bytes()` returns a zero-copy, read-only memoryview of the collected Rust
-buffer. Collecting the body may allocate to join chunks. Views stay valid after
-the response closes; see [binary data](../getting-started/quickstart.md#binary-data)
-for decoding, copying and releasing them.
+`bytes()` returns a zero-copy `wreq.Bytes` of the collected Rust buffer.
+Collecting the body may allocate to join chunks. The data stays valid after the
+response closes; see [binary data](../getting-started/quickstart.md#binary-data)
+for decoding and copying it.
## Concurrent requests
@@ -253,7 +253,7 @@ propagate when a caller cancels your task.
## Streaming responses
Read large bodies incrementally with `response.stream()`. Data frames are
-read-only memoryviews, and trailing HTTP headers are `HeaderMap` objects.
+`wreq.Bytes`, and trailing HTTP headers are `HeaderMap` objects.
This complete example counts the bytes without retaining the whole body:
```python
@@ -269,10 +269,10 @@ async def main():
response.raise_for_status()
async with response.stream() as streamer:
async for frame in streamer:
- if isinstance(frame, memoryview):
- total += len(frame)
- elif isinstance(frame, HeaderMap):
+ if isinstance(frame, HeaderMap):
print("Trailers:", frame)
+ else:
+ total += len(frame)
print("Received bytes:", total)
diff --git a/docs/source/guide/blocking.md b/docs/source/guide/blocking.md
index 96131f96..3ecd6d72 100644
--- a/docs/source/guide/blocking.md
+++ b/docs/source/guide/blocking.md
@@ -111,7 +111,7 @@ Closing a client cancels pending requests and rejects new ones with
## Streaming response
-`response.bytes()` returns a read-only memoryview of the complete body. To
+`response.bytes()` returns a zero-copy `wreq.Bytes` of the complete body. To
write a large response incrementally, use a streamer:
```python
@@ -124,14 +124,14 @@ with Client() as client:
response.raise_for_status()
with response.stream() as streamer, open("download.bin", "wb") as output:
for frame in streamer:
- if isinstance(frame, memoryview):
- output.write(frame)
- elif isinstance(frame, HeaderMap):
+ if isinstance(frame, HeaderMap):
print("Trailers:", frame)
+ else:
+ output.write(frame)
```
-Data views remain valid after the stream closes. `output.write(frame)` accepts
-the buffer directly; `bytes(frame)` makes a copy. Only an unread response can
+Data frames remain valid after the stream closes. `output.write(frame)` accepts
+the buffer directly; `frame.tobytes()` makes a copy. Only an unread response can
be streamed. Complete body reads through `text()`, `json()` or `bytes()` are
cached and can be repeated sequentially until the response is released.
diff --git a/docs/source/guide/redirect-errors.md b/docs/source/guide/redirect-errors.md
index 1ae03843..8014d493 100644
--- a/docs/source/guide/redirect-errors.md
+++ b/docs/source/guide/redirect-errors.md
@@ -26,7 +26,7 @@ async def main():
print(response.status)
location = response.headers.get("location")
if location is not None:
- print("Location:", bytes(location).decode())
+ print("Location:", location.decode())
await response.bytes()
diff --git a/docs/source/guide/websocket.md b/docs/source/guide/websocket.md
index 442923e4..cf895760 100644
--- a/docs/source/guide/websocket.md
+++ b/docs/source/guide/websocket.md
@@ -41,10 +41,11 @@ Use `Message.from_binary(data)` to send binary data. `send_all([...])` sends
a sequence of messages in order. To choose the closing status, call
`await ws.close(code=1000, reason="Finished")` before leaving the context.
-Binary payload access is zero-copy: `Message.data`, `.binary`, `.ping`, and
-`.pong` return read-only `memoryview` objects when present. The views remain
-valid after the message is deleted or the connection closes. Use `bytes(view)`
-when another API requires a `bytes` object; `Message.text` returns a string.
+Binary payload access is zero-copy: `Message.data` and `.binary` return
+`wreq.Bytes` when present, which stay valid after the message is deleted or the
+connection closes. `.ping` and `.pong` return `bytes`, since RFC 6455 limits
+control payloads to 125 bytes. Use `data.tobytes()` when another API requires a
+`bytes` object; `Message.text` returns a string.
## Receive timeouts
diff --git a/docs/source/index.md b/docs/source/index.md
index 285d5ab9..058d4183 100644
--- a/docs/source/index.md
+++ b/docs/source/index.md
@@ -81,7 +81,7 @@ asyncio.run(main())
02 · PERFORMANCE
Blocking API
diff --git a/examples/blocking/stream.py b/examples/blocking/stream.py
index a3bda692..72a8ab69 100644
--- a/examples/blocking/stream.py
+++ b/examples/blocking/stream.py
@@ -9,10 +9,10 @@ def main():
with wreq.blocking.get("https://httpbin.io/stream/20") as resp:
with resp.stream() as streamer:
for chunk in streamer:
- if isinstance(chunk, memoryview):
- sys.stdout.buffer.write(chunk)
- else:
+ if isinstance(chunk, wreq.HeaderMap):
print("Trailers:", chunk)
+ else:
+ sys.stdout.buffer.write(chunk)
time.sleep(0.1)
diff --git a/examples/bytes.py b/examples/bytes.py
new file mode 100644
index 00000000..774c3bbb
--- /dev/null
+++ b/examples/bytes.py
@@ -0,0 +1,26 @@
+import asyncio
+import hashlib
+import json
+
+import wreq
+
+
+async def main():
+ async with wreq.Client() as client:
+ async with client.get("https://httpbin.io/json") as resp:
+ # An immutable wreq.Bytes that shares the body without copying.
+ data = await resp.bytes()
+
+ # Buffer APIs read it in place, and slices share it too.
+ print(hashlib.sha256(data).hexdigest(), data[:16])
+
+ # json.loads() takes only str, bytes or bytearray.
+ print(json.loads(data.decode())["slideshow"]["title"])
+
+ # Passing it back as a request body does not copy it.
+ async with client.post("https://httpbin.io/anything", body=data) as resp:
+ print(resp.status)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/examples/stream.py b/examples/stream.py
index 79552d1a..dd16f8b2 100644
--- a/examples/stream.py
+++ b/examples/stream.py
@@ -7,10 +7,10 @@ async def main():
async with wreq.get("https://httpbin.io/stream/20") as resp:
async with resp.stream() as streamer:
async for chunk in streamer:
- if isinstance(chunk, memoryview):
- sys.stdout.buffer.write(chunk)
- else:
+ if isinstance(chunk, wreq.HeaderMap):
print("Trailers:", chunk)
+ else:
+ sys.stdout.buffer.write(chunk)
await asyncio.sleep(0.1)
diff --git a/python/wreq/__init__.py b/python/wreq/__init__.py
index 9dc0c8d4..40ddd9a0 100644
--- a/python/wreq/__init__.py
+++ b/python/wreq/__init__.py
@@ -1,5 +1,7 @@
# wreq/__init__.py
+from collections.abc import Sequence as _Sequence
+
from .wreq import *
from .cookie import *
@@ -14,6 +16,9 @@
from .proxy import *
from .runtime import *
+# A Sequence like `bytes`; like `memoryview`, it also matches sequence patterns in `match`.
+_Sequence.register(Bytes) # pyright: ignore[reportAttributeAccessIssue]
+
__all__ = (
header.__all__
+ cookie.__all__
diff --git a/python/wreq/blocking.py b/python/wreq/blocking.py
index f1f454d7..33579e38 100644
--- a/python/wreq/blocking.py
+++ b/python/wreq/blocking.py
@@ -22,6 +22,7 @@
from .redirect import History
from .runtime import Runtime
from .tls import TlsInfo
+from .wreq import Bytes
class Response:
@@ -86,7 +87,7 @@ def raise_for_status(self) -> None:
def stream(self) -> Streamer:
r"""
- Stream the body as read-only memoryviews, with HeaderMap frames for trailers.
+ Stream the body as immutable `Bytes`, with HeaderMap frames for trailers.
"""
...
@@ -101,11 +102,12 @@ def json(self) -> Any:
Get the JSON content of the response.
"""
- def bytes(self) -> memoryview:
+ def bytes(self) -> Bytes:
r"""
- Read the body as a read-only memoryview without copying it into Python bytes.
- The view remains valid after the response is closed or deleted.
- Use bytes(view) or view.tobytes() for a copy; view.release() releases this view.
+ Read the body as an immutable `Bytes` without copying it.
+ The data stays valid after the response is closed or deleted.
+ Use `data.tobytes()` for a `bytes` copy, or `memoryview(data)` for APIs that accept
+ only `bytes`, `bytearray` or `memoryview`.
"""
...
@@ -114,7 +116,7 @@ def close(self) -> None:
Discard the retained body and mark its connection as non-reusable.
This does not guarantee an immediate socket shutdown or interrupt an active read.
Do not close concurrently with a body read. A body transferred to a Streamer
- is managed separately; previously returned memoryviews remain valid.
+ is managed separately; previously returned `Bytes` remain valid.
`with` instead releases the body and keeps a fully read connection reusable.
"""
diff --git a/python/wreq/header.py b/python/wreq/header.py
index 406e53d2..9e1a53eb 100644
--- a/python/wreq/header.py
+++ b/python/wreq/header.py
@@ -13,6 +13,8 @@
from typing import Iterator, Tuple
+from .wreq import Bytes
+
__all__ = ["HeaderMap", "OrigHeaderMap"]
@@ -28,11 +30,10 @@ class HeaderMap:
and provides both dictionary-like access and specialized methods for
HTTP header manipulation.
- Header names and values are returned as read-only memoryviews.
- Each view retains its backing data even if the map is changed or deleted.
+ Header names and values are returned as `bytes` copies.
"""
- def __getitem__(self, key: str) -> memoryview | None:
+ def __getitem__(self, key: str) -> bytes | None:
"""Get the first value for a header name (case-insensitive)."""
...
@@ -52,7 +53,7 @@ def __len__(self) -> int:
"""Return the total number of header values (not unique names)."""
...
- def __iter__(self) -> Iterator[Tuple[memoryview, memoryview]]:
+ def __iter__(self) -> Iterator[Tuple[bytes, bytes]]:
"""Iterate all header(name, value) pairs, including duplicates for multiple values."""
...
@@ -143,7 +144,9 @@ def remove(self, key: str) -> None:
"""
...
- def get(self, key: str, default: bytes | None = None) -> memoryview | None:
+ def get(
+ self, key: str, default: bytes | bytearray | memoryview | Bytes | None = None
+ ) -> bytes | None:
r"""
Get the first value for a header name with optional default.
@@ -156,15 +159,15 @@ def get(self, key: str, default: bytes | None = None) -> memoryview | None:
default: Value to return if header doesn't exist
Returns:
- A read-only view of the first header value, or of the default value
+ The first header value, or the default value, as `bytes`
"""
...
- def get_all(self, key: str) -> list[memoryview]:
+ def get_all(self, key: str) -> list[bytes]:
r"""
Get all values for a header name.
- Returns a list of read-only views of all values associated with the header name.
+ Returns a list of all values associated with the header name.
This is useful for headers that can have multiple values, such as
Set-Cookie, Accept-Encoding, or custom headers.
@@ -172,25 +175,25 @@ def get_all(self, key: str) -> list[memoryview]:
key: The header name (case-insensitive)
Returns:
- A list of read-only header value views
+ A list of header values as `bytes`
"""
...
- def values(self) -> list[memoryview]:
+ def values(self) -> list[bytes]:
"""
Get all header values.
Returns:
- A list of read-only header value views.
+ A list of header values as `bytes`.
"""
...
- def keys(self) -> list[memoryview]:
+ def keys(self) -> list[bytes]:
"""
Get all unique header names.
Returns:
- A list of read-only header name views.
+ A list of header names as `bytes`.
"""
...
@@ -250,7 +253,7 @@ class OrigHeaderMap:
The map stores a mapping between the case-insensitive (standard) header name and the
original case-sensitive header name as it appeared in the HTTP message.
- Iteration returns pairs of read-only memoryviews that retain their backing data.
+ Iteration returns pairs of `bytes`.
Example:
If an HTTP message included the following headers:
@@ -282,7 +285,7 @@ def __init__(
"""
...
- def __iter__(self) -> Iterator[Tuple[memoryview, memoryview]]:
+ def __iter__(self) -> Iterator[Tuple[bytes, bytes]]:
"""
Returns an iterator over the (standard_name, original_name) pairs.
diff --git a/python/wreq/tls.py b/python/wreq/tls.py
index b1662cad..e5db58fb 100644
--- a/python/wreq/tls.py
+++ b/python/wreq/tls.py
@@ -6,7 +6,11 @@
from enum import Enum, auto
from pathlib import Path
-from typing import Sequence, NotRequired, TypedDict, Unpack, final
+from typing import Sequence, NotRequired, TypeAlias, TypedDict, Unpack, final
+
+from .wreq import Bytes
+
+_BytesLike: TypeAlias = "bytes | bytearray | memoryview | Bytes"
__all__ = [
"TlsVersion",
@@ -134,7 +138,7 @@ class Identity:
"""
@staticmethod
- def from_pkcs12_der(buf: bytes, pass_: str, /) -> "Identity":
+ def from_pkcs12_der(buf: _BytesLike, pass_: str, /) -> "Identity":
"""
Parses a DER-formatted PKCS #12 archive, using the specified password to decrypt the key.
Pass the archive and password positionally: Identity.from_pkcs12_der(data, password).
@@ -151,7 +155,7 @@ def from_pkcs12_der(buf: bytes, pass_: str, /) -> "Identity":
...
@staticmethod
- def from_pkcs8_pem(buf: bytes, key: bytes) -> "Identity":
+ def from_pkcs8_pem(buf: _BytesLike, key: _BytesLike) -> "Identity":
"""
Parses a chain of PEM encoded X509 certificates, with the leaf certificate first.
`key` is a PEM encoded PKCS #8 formatted private key for the leaf certificate.
@@ -172,7 +176,7 @@ class CertStore:
def __init__(
self,
- der_certs: Sequence[bytes] | None = None,
+ der_certs: Sequence[_BytesLike] | None = None,
pem_certs: Sequence[str] | None = None,
default_paths: bool = False,
) -> None:
@@ -180,19 +184,19 @@ def __init__(
Creates a new CertStore.
Args:
- der_certs: Optional list of DER-encoded certificates (as bytes).
+ der_certs: Optional list of DER-encoded certificates (bytes-like).
pem_certs: Optional list of PEM-encoded certificates (as str).
default_paths: If True, use system default certificate paths. Defaults to False.
"""
...
@staticmethod
- def from_der_certs(certs: Sequence[bytes]) -> "CertStore":
+ def from_der_certs(certs: Sequence[_BytesLike]) -> "CertStore":
"""
Creates a CertStore from a collection of DER-encoded certificates.
Args:
- certs: List of DER-encoded certificates (as bytes).
+ certs: List of DER-encoded certificates (bytes-like).
"""
...
@@ -207,12 +211,12 @@ def from_pem_certs(certs: Sequence[str]) -> "CertStore":
...
@staticmethod
- def from_pem_stack(certs: bytes) -> "CertStore":
+ def from_pem_stack(certs: _BytesLike) -> "CertStore":
"""
Creates a CertStore from a PEM-encoded certificate stack.
Args:
- certs: PEM-encoded certificate stack (as bytes).
+ certs: PEM-encoded certificate stack (bytes-like).
"""
...
@@ -426,7 +430,7 @@ class Params(TypedDict):
Whether the `signature_algorithms` extension includes a GREASE value.
"""
- trust_anchors: NotRequired[bytes]
+ trust_anchors: NotRequired[_BytesLike]
"""
Encoded Trust Anchor IDs sent in a TLS 1.3 ClientHello.
"""
@@ -460,8 +464,8 @@ class TlsInfo:
Information about the established TLS connection.
"""
- def peer_certificate(self) -> memoryview | None:
+ def peer_certificate(self) -> bytes | None:
"""
- Get a read-only memoryview of the peer's DER-encoded leaf certificate.
+ Get the peer's DER-encoded leaf certificate as `bytes`.
"""
...
diff --git a/python/wreq/wreq.py b/python/wreq/wreq.py
index 4662ea41..85d48ea5 100644
--- a/python/wreq/wreq.py
+++ b/python/wreq/wreq.py
@@ -12,13 +12,19 @@
Sequence,
Mapping,
Tuple,
+ TypeAlias,
TypedDict,
TypeVar,
Unpack,
final,
+ overload,
+ SupportsIndex,
+ Iterator,
)
from collections.abc import Coroutine
+from typing_extensions import Buffer, deprecated
+
from . import redirect
from . import emulation
from .cookie import *
@@ -32,6 +38,160 @@
from .runtime import Runtime
from .tls import *
+_BytesLike: TypeAlias = "bytes | bytearray | memoryview | Bytes"
+
+
+@final
+class Bytes(Sequence[int], Buffer):
+ r"""
+ Immutable binary data returned by wreq without copying.
+
+ It exports a read-only buffer, so `memoryview(data)`, `hashlib`, `bytes.join`, `socket.send`
+ and `numpy.frombuffer` read it in place. It compares and hashes like `bytes`, so it works as
+ a `bytes` dictionary key. `data.tobytes()` makes a copy for APIs that require `bytes`, such
+ as `json.loads` or `isinstance(x, bytes)` checks; `memoryview(data)` suits APIs that accept
+ only `bytes`, `bytearray` or `memoryview`, such as asyncio transports and `orjson.loads`.
+ wreq accepts it wherever it accepts `bytes`.
+ """
+
+ def __new__(cls, data: Buffer | None = None, /) -> Self:
+ r"""
+ Wrap any buffer. `bytes`, a `Bytes` (returned as is) and contiguous memoryviews of either
+ are shared and keep their whole source alive; other data is copied. Wrap
+ `view.tobytes()` for a compact copy.
+ """
+ ...
+
+ def __buffer__(self, flags: int, /) -> memoryview: ...
+ def __len__(self) -> int: ...
+ @overload
+ def __getitem__(self, key: SupportsIndex, /) -> int: ...
+ @overload
+ def __getitem__(self, key: slice, /) -> "Bytes": ...
+ def __getitem__(self, key: SupportsIndex | slice, /) -> "int | Bytes":
+ r"""
+ An int for an index. A slice shares memory with this data unless it is strided, which
+ copies.
+ """
+ ...
+
+ def __iter__(self) -> Iterator[int]: ...
+ def __contains__(self, item: SupportsIndex | Buffer, /) -> bool: # type: ignore[override]
+ r"""
+ Whether `item`, a buffer or a byte value, occurs in this data.
+ """
+ ...
+
+ def __eq__(self, other: object, /) -> bool: ...
+ def __ne__(self, other: object, /) -> bool: ...
+ def __lt__(self, other: "bytes | Bytes", /) -> bool: ...
+ def __le__(self, other: "bytes | Bytes", /) -> bool: ...
+ def __gt__(self, other: "bytes | Bytes", /) -> bool: ...
+ def __ge__(self, other: "bytes | Bytes", /) -> bool: ...
+ def __hash__(self) -> int: ...
+ def __bytes__(self) -> bytes: ...
+ def __add__(self, other: Buffer, /) -> "Bytes":
+ r"""
+ Concatenate with any buffer into a new `Bytes`.
+ """
+ ...
+
+ def __copy__(self) -> Self: ...
+ def __deepcopy__(self, memo: Any, /) -> Self: ...
+ def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
+ r"""
+ Decode into `str`, like `bytes.decode()`.
+ """
+ ...
+
+ def hex(self, sep: str | bytes | None = None, bytes_per_sep: int = 1) -> str:
+ r"""
+ Hexadecimal digits for each byte, like `bytes.hex()`.
+ """
+ ...
+
+ def tobytes(self) -> bytes:
+ r"""
+ Copy into `bytes`, like `memoryview.tobytes()`; cheaper than `bytes(data)`.
+ """
+ ...
+
+ def find(
+ self,
+ sub: SupportsIndex | Buffer,
+ start: SupportsIndex | None = None,
+ end: SupportsIndex | None = None,
+ /,
+ ) -> int:
+ r"""
+ The lowest index of `sub`, a buffer or a byte value, within `[start:end]`, or `-1`.
+ """
+ ...
+
+ def index(
+ self,
+ sub: SupportsIndex | Buffer,
+ start: SupportsIndex | None = None,
+ end: SupportsIndex | None = None,
+ /,
+ ) -> int:
+ r"""
+ Like `find()`, but raise `ValueError` when `sub` is not found.
+ """
+ ...
+
+ def count(
+ self,
+ sub: SupportsIndex | Buffer,
+ start: SupportsIndex | None = None,
+ end: SupportsIndex | None = None,
+ /,
+ ) -> int:
+ r"""
+ The number of non-overlapping occurrences of `sub` within `[start:end]`.
+ """
+ ...
+
+ def startswith(
+ self,
+ prefix: Buffer | tuple[Buffer, ...],
+ start: SupportsIndex | None = None,
+ end: SupportsIndex | None = None,
+ /,
+ ) -> bool:
+ r"""
+ Whether `[start:end]` starts with `prefix` or with any prefix in a tuple.
+ """
+ ...
+
+ def endswith(
+ self,
+ suffix: Buffer | tuple[Buffer, ...],
+ start: SupportsIndex | None = None,
+ end: SupportsIndex | None = None,
+ /,
+ ) -> bool:
+ r"""
+ Whether `[start:end]` ends with `suffix` or with any suffix in a tuple.
+ """
+ ...
+
+ @deprecated("Bytes holds no exported view; drop the reference instead")
+ def release(self) -> None:
+ r"""
+ Does nothing and warns; kept for code written against `memoryview`.
+ """
+ ...
+
+ @deprecated("Bytes is not a context manager; use `with memoryview(data) as view:`")
+ def __enter__(self) -> Self:
+ r"""
+ Returns this data and warns; kept for code written against `memoryview`.
+ """
+ ...
+
+ def __exit__(self, *args: object) -> None: ...
+
@final
class Method(Enum):
@@ -153,9 +313,12 @@ def __init__(
value: (
str
| bytes
+ | bytearray
+ | memoryview
+ | Bytes
| Path
- | Generator[bytes, str, None]
- | AsyncGenerator[bytes, str]
+ | Generator[_BytesLike | str, str, None]
+ | AsyncGenerator[_BytesLike | str, str]
),
filename: str | None = None,
mime: str | None = None,
@@ -183,12 +346,13 @@ class Message:
r"""
A WebSocket message.
- Binary fields return read-only memoryviews that retain their backing data.
+ `data` and `binary` return immutable `Bytes` that retain their backing data;
+ `ping` and `pong` return `bytes`, since RFC 6455 limits control payloads to 125 bytes.
"""
- data: memoryview | None
+ data: Bytes | None
r"""
- Returns the data of the message as a read-only memoryview.
+ Returns the data of the message as an immutable `Bytes`.
"""
text: str | None
@@ -196,17 +360,17 @@ class Message:
Returns the text content of the message if it is a text message.
"""
- binary: memoryview | None
+ binary: Bytes | None
r"""
Returns the binary data of the message if it is a binary message.
"""
- ping: memoryview | None
+ ping: bytes | None
r"""
Returns the ping data of the message if it is a ping message.
"""
- pong: memoryview | None
+ pong: bytes | None
r"""
Returns the pong data of the message if it is a pong message.
"""
@@ -222,7 +386,7 @@ class Message:
"""
@staticmethod
- def from_binary(like: bytes | Any) -> "Message":
+ def from_binary(like: bytes | bytearray | memoryview | Bytes | Any) -> "Message":
r"""
Creates a new binary message.
@@ -244,7 +408,7 @@ def from_text(like: str | Any) -> "Message":
...
@staticmethod
- def from_ping(data: bytes) -> "Message":
+ def from_ping(data: bytes | bytearray | memoryview | Bytes) -> "Message":
r"""
Creates a new ping message.
@@ -255,7 +419,7 @@ def from_ping(data: bytes) -> "Message":
...
@staticmethod
- def from_pong(data: bytes) -> "Message":
+ def from_pong(data: bytes | bytearray | memoryview | Bytes) -> "Message":
r"""
Creates a new pong message.
@@ -283,14 +447,14 @@ def __str__(self) -> str: ...
class Streamer:
r"""
A stream response.
- An asynchronous iterator yielding read-only memoryviews or HTTP trailers (HeaderMap) from the response stream.
+ An asynchronous iterator yielding immutable `Bytes` or HTTP trailers (HeaderMap) from the response stream.
Used to stream response content and receive HTTP trailers if present.
Implemented in the `stream` method of the `Response` class.
Can be used in an asynchronous for loop in Python.
- When streaming a response, each iteration yields either a memoryview (for body data) or a HeaderMap (for HTTP trailers, if the server sends them).
+ When streaming a response, each iteration yields either a `Bytes` (for body data) or a HeaderMap (for HTTP trailers, if the server sends them).
This allows you to access HTTP/1.1 or HTTP/2 trailers in addition to the main body.
- Data views retain their backing data after the stream is closed.
+ Data frames stay valid after the stream is closed.
A stream on a `CURRENT_THREAD` runtime supports only blocking iteration;
its async entry points raise `RuntimeError`.
@@ -306,10 +470,10 @@ async def main():
async with wreq.get("https://example.com/stream-with-trailers") as resp:
async with resp.stream() as streamer:
async for chunk in streamer:
- if isinstance(chunk, memoryview):
- sys.stdout.buffer.write(chunk)
- elif isinstance(chunk, HeaderMap):
+ if isinstance(chunk, HeaderMap):
print("Trailers: ", chunk)
+ else:
+ sys.stdout.buffer.write(chunk)
await asyncio.sleep(0.1)
if __name__ == "__main__":
@@ -319,24 +483,24 @@ async def main():
def __iter__(self) -> "Streamer": ...
- def __next__(self) -> memoryview | HeaderMap: ...
+ def __next__(self) -> Bytes | HeaderMap: ...
def __enter__(self) -> Self: ...
def __exit__(self, _exc_type: Any, _exc_value: Any, _traceback: Any) -> None:
r"""
- Release the body and end any pending read; returned views stay valid.
+ Release the body and end any pending read; returned data stays valid.
"""
def __aiter__(self) -> "Streamer": ...
- async def __anext__(self) -> memoryview | HeaderMap: ...
+ async def __anext__(self) -> Bytes | HeaderMap: ...
async def __aenter__(self) -> Self: ...
async def __aexit__(self, _exc_type: Any, _exc_value: Any, _traceback: Any) -> None:
r"""
- Release the body and end any pending read; returned views stay valid.
+ Release the body and end any pending read; returned data stays valid.
"""
@@ -424,7 +588,7 @@ def raise_for_status(self) -> None:
def stream(self) -> Streamer:
r"""
- Stream the body as read-only memoryviews, with HeaderMap frames for trailers.
+ Stream the body as immutable `Bytes`, with HeaderMap frames for trailers.
"""
...
@@ -439,11 +603,12 @@ async def json(self) -> Any:
Get the JSON content of the response.
"""
- async def bytes(self) -> memoryview:
+ async def bytes(self) -> Bytes:
r"""
- Read the body as a read-only memoryview without copying it into Python bytes.
- The view remains valid after the response is closed or deleted.
- Use bytes(view) or view.tobytes() for a copy; view.release() releases this view.
+ Read the body as an immutable `Bytes` without copying it.
+ The data stays valid after the response is closed or deleted.
+ Use `data.tobytes()` for a `bytes` copy, or `memoryview(data)` for APIs that accept
+ only `bytes`, `bytearray` or `memoryview`.
"""
...
@@ -452,7 +617,7 @@ async def close(self) -> None:
Discard the retained body and mark its connection as non-reusable.
This does not guarantee an immediate socket shutdown or cancel an active read.
Cancel and await any body-read task before closing. A body transferred to a
- Streamer is managed separately; previously returned memoryviews remain valid.
+ Streamer is managed separately; previously returned `Bytes` remain valid.
`async with` instead releases the body and keeps a fully read connection reusable.
"""
@@ -979,12 +1144,15 @@ class Request(TypedDict):
body: NotRequired[
str
| bytes
+ | bytearray
+ | memoryview
+ | Bytes
| Sequence[Tuple[str, str]]
| Tuple[str, str | int | float | bool]
| Mapping[str, str | int | float | bool]
| Any
- | Generator[bytes, str, None]
- | AsyncGenerator[bytes, str]
+ | Generator[_BytesLike | str, str, None]
+ | AsyncGenerator[_BytesLike | str, str]
]
"""
The body to use for the request.
diff --git a/src/buffer.rs b/src/buffer.rs
index 7b3d8231..76573277 100644
--- a/src/buffer.rs
+++ b/src/buffer.rs
@@ -15,30 +15,129 @@
// specific language governing permissions and limitations
// under the License.
-use std::os::raw::c_int;
+use std::{
+ ffi::CString,
+ ops::{Deref, Range},
+ os::raw::c_int,
+ sync::atomic::{AtomicIsize, AtomicUsize, Ordering},
+};
-use bytes::Bytes;
-use pyo3::{exceptions::PyOverflowError, ffi, prelude::*, types::PyMemoryView};
-use wreq::header::{HeaderCaseName, HeaderName, HeaderValue};
+use bytes::{Buf, Bytes};
+use memchr::memmem;
+use pyo3::{
+ IntoPyObjectExt, PyTypeCheck, PyTypeInfo,
+ buffer::PyUntypedBuffer,
+ exceptions::{
+ PyDeprecationWarning, PyIndexError, PyMemoryError, PyOverflowError, PyTypeError,
+ PyValueError,
+ },
+ ffi, intern,
+ prelude::*,
+ pybacked::PyBackedBytes,
+ pyclass::CompareOp,
+ sync::PyOnceLock,
+ types::{
+ PyBool, PyByteArray, PyBytes, PyInt, PyMemoryView, PySlice, PyString, PyTuple, PyType,
+ slice::PySliceIndices,
+ },
+};
-/// Exposes owned Rust bytes as a read-only Python memoryview without copying.
-pub struct PyBuffer(BufferView);
+/// Bytes shared with Python in both directions: extracted from `bytes`, `bytearray`,
+/// `memoryview` or `wreq.Bytes` input and returned as an immutable `wreq.Bytes`.
+///
+/// Input is shared only when an exact `bytes`, a `wreq.Bytes` or a memoryview of either owns
+/// it. Mutable exporters and subclasses are copied, so a `Bytes` never aliases writable memory
+/// or hides a reference cycle from the GC.
+#[derive(Clone)]
+pub struct PyBuffer(pub Bytes);
-/// The exporter behind each memoryview; views keep it, and so its bytes, alive.
-#[pyclass(frozen)]
-struct BufferView(Bytes);
+/// Immutable binary data shared without copying. It exports a read-only buffer and compares
+/// and hashes like `bytes`; `bytes(data)` makes a copy.
+// Its owners are exact `bytes` or Rust data, so it cannot hide a reference cycle, and it
+// allows no subclasses, so an exact type test finds every instance.
+#[pyclass(name = "Bytes", module = "wreq", frozen, sequence, weakref)]
+pub struct SharedBytes {
+ bytes: Bytes,
+ /// `hash(bytes(self))` once computed, otherwise [`UNHASHED`].
+ hash: AtomicIsize,
+}
+
+/// Iterates the ints of a `wreq.Bytes`; threads sharing it each take distinct bytes.
+#[pyclass(name = "BytesIterator", module = "wreq", frozen)]
+struct BytesIter {
+ bytes: Bytes,
+ next: AtomicUsize,
+}
+
+/// A `start` or `end` argument. Ints beyond `isize` clamp, as CPython clamps slice indices.
+#[derive(Clone, Copy)]
+struct SliceIndex(isize);
+
+/// Bytes-like data read in place, or extracted when it cannot be.
+enum Operand<'a> {
+ Borrowed(&'a [u8]),
+ Owned(Bytes),
+}
+
+/// What `find`, `count` and `in` look for: a subsequence or a single byte.
+enum Needle<'a> {
+ Byte(u8),
+ Seq(Operand<'a>),
+}
+
+/// Python hashes are never `-1`, which marks an uncomputed hash.
+const UNHASHED: isize = -1;
// ===== impl PyBuffer =====
+impl PyBuffer {
+ /// Extracts `bytes`, `bytearray`, `memoryview` or `wreq.Bytes` data in one pass over their
+ /// types, or returns `None` for any other type without building an error, so callers can
+ /// fall back.
+ pub fn extract_bytes_like(ob: &Bound) -> Option> {
+ let bytes = if let Some(bytes) = as_exact::(ob) {
+ let owner = PyBackedBytes::from(bytes.clone());
+ share(0..owner.len(), owner)
+ } else if let Some(shared) = as_exact::(ob) {
+ // A counted clone, without a round trip through the buffer protocol.
+ shared.get().bytes.clone()
+ } else if let Some(view) = as_exact::(ob) {
+ return Some(view_bytes(view).map(Self));
+ } else if let Some(array) = as_instance::(ob) {
+ // A bytearray may change after extraction, so it is copied once.
+ Bytes::from(array.to_vec())
+ } else {
+ // Subclasses can reference an exported view; Bytes owners are invisible to GC.
+ Bytes::copy_from_slice(as_instance::(ob)?.as_bytes())
+ };
+ Some(Ok(Self(bytes)))
+ }
+}
+
+impl FromPyObject<'_, '_> for PyBuffer {
+ type Error = PyErr;
+
+ fn extract(ob: Borrowed) -> PyResult {
+ match Self::extract_bytes_like(&ob) {
+ Some(bytes) => bytes,
+ // Other exporters, such as numpy numbers or `array('d')`, count as bytes only in a
+ // memoryview, so `body=` and `from_binary` keep encoding them as JSON.
+ None => Err(not_instance_of(
+ &ob,
+ "bytes | bytearray | memoryview | Bytes",
+ )),
+ }
+ }
+}
+
impl<'a> IntoPyObject<'a> for PyBuffer {
- type Target = PyMemoryView;
+ type Target = SharedBytes;
type Output = Bound<'a, Self::Target>;
type Error = PyErr;
#[inline(always)]
fn into_pyobject(self, py: Python<'a>) -> Result {
- let buffer = self.0.into_pyobject(py)?;
- PyMemoryView::from(buffer.as_any())
+ Bound::new(py, SharedBytes::from(self.0))
}
}
@@ -59,45 +158,104 @@ impl From<&Bytes> for PyBuffer {
impl From for PyBuffer {
#[inline]
fn from(value: Bytes) -> Self {
- PyBuffer(BufferView(value))
+ PyBuffer(value)
}
}
-impl From for PyBuffer {
+impl AsRef<[u8]> for PyBuffer {
#[inline]
- fn from(value: HeaderName) -> Self {
- Self::from(Bytes::from_owner(value))
+ fn as_ref(&self) -> &[u8] {
+ &self.0
}
}
-impl From for PyBuffer {
- fn from(value: HeaderCaseName) -> Self {
- Self::from(Bytes::from_owner(value))
- }
-}
+// ===== impl SharedBytes =====
-impl From for PyBuffer {
+impl From for SharedBytes {
#[inline]
- fn from(value: HeaderValue) -> Self {
- Self::from(Bytes::from_owner(value))
+ fn from(bytes: Bytes) -> Self {
+ Self {
+ bytes,
+ hash: AtomicIsize::new(UNHASHED),
+ }
}
}
-// ===== impl BufferView =====
+impl SharedBytes {
+ /// The first index of `sub` within `[start:end]`.
+ fn position(
+ &self,
+ sub: &Bound,
+ start: Option,
+ end: Option,
+ ) -> PyResult