CodeSampleX

Beispiel

requests 2.34.2: Verify requests 2.34.2 BaseAdapter.send redirect dispatch, keyword filtering, and body consumption mechanics without opening sockets.

Verifiziertes Beispiel für pypi requests 2.34.2: Verify requests 2.34.2 BaseAdapter.send redirect dispatch, keyword filtering, and body consumption mechanics…

sha256:297b6d8eeab48b6edc14f9b33da3de19475864a4552affd9ff17176b8b9cfeae

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
2
Signaturschlüssel, die es gebaut haben
2
Deklarierte Umgebung python linux x64 python python pip

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-18
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-18

Fall

HOW
Ziel
Verify requests 2.34.2 BaseAdapter.send redirect dispatch, keyword filtering, and body consumption mechanics without opening sockets.
Pakete
Symbole
  • requests.adapters.BaseAdapter
  • requests.adapters.BaseAdapter.send
  • requests.Session.send
  • requests.Session.mount
  • requests.PreparedRequest
  • requests.Response
Umgebung
python
Erstellt
2026-08-18T01:21:27Z

Contract

  1. BaseAdapter.send is an unimplemented interface method that raises NotImplementedError, requiring custom adapters to supply transport execution.
  2. Session.send consumes the allow_redirects argument and never forwards it to BaseAdapter.send keyword arguments.
  3. When BaseAdapter.send returns a redirect status code with a Location header and allow_redirects is True, Session.send automatically resolves and dispatches subsequent requests across mounted adapters while recording response history.
  4. When allow_redirects is False, Session.send populates the next PreparedRequest on response.next without invoking BaseAdapter.send for subsequent hops.
  5. Session.send eagerly consumes unread raw streams returned by BaseAdapter.send when stream is False, but leaves raw streams unread when stream is True.

Dateien

  • NOTES.md
  • csx.json
  • requirements.txt
  • test/contract.py

Quellartefakt herunterladen (tar.gz)

Quelltext

NOTES.md
# Requests 2.34.2 `BaseAdapter.send` Transport Mechanics

## Search Results and Context
A query for `requests.adapters.BaseAdapter.send` matched sample `sha256:6f55c9b338df69b57b0fe94cc3f4299ac9b37f3a1e14983a6706d0e3e2bf96cf`, which proved that `BaseAdapter.send` raises `NotImplementedError` and verified basic custom adapter mounting. This sample explores the broader contract of `BaseAdapter.send` during redirect resolution, option filtering, and stream body consumption.

## Pinned Release
- `requests==2.34.2`

## Observed Behaviour
- **Abstract Transport Interface**: `BaseAdapter.send` defines the transport boundary `(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None)` and unconditionally raises `NotImplementedError`. Subclasses must provide a concrete implementation.
- **Redirect Filtering**: When `Session.send` executes, it extracts and pops `allow_redirects` before dispatching to `BaseAdapter.send`. The transport adapter never receives `allow_redirects` in its keyword arguments.
- **Redirect Resolution Across Adapters**: If a custom adapter's `send()` returns a 3xx redirect status code with a `Location` header and `allow_redirects=True`, `Session.send` resolves the redirect target, selects the appropriate adapter for the target URL scheme/prefix, calls that adapter's `send()` method, and tracks prior responses in `response.history`.
- **Deferred Redirection with `response.next`**: When `allow_redirects=False`, `Session.send` halts after the first `send()` call, populating `response.next` with the prepared next hop without invoking the transport adapter for that hop.
- **Stream Body Consumption**: When `stream=False` (default), `Session.send` immediately consumes unread data from `response.raw` into `response._content`. When `stream=True`, `response.raw` is left unread so callers can stream the content on demand.

## Failure Mode of Incorrect Assumptions
- Developers expecting `allow_redirects` to be passed to custom adapters or trying to implement redirect handling within `BaseAdapter.send` will find `allow_redirects` absent from `kwargs`, causing duplicate redirects or unexpected parameter errors if `allow_redirects` is required.
- Adapters returning an unread stream in `response.raw` without handling `stream=False` will have their streams eagerly read and cached by `Session.send` before the caller receives the `Response`.
csx.json
{"case":{"believed":"Custom transport adapters receive allow_redirects directly in send() kwargs and must handle redirect following themselves.","caseId":"case:sha256:2d57bec36d5e64b7d49a5e32a92befc1d90966597c02c97177a5b5429595e26d","contract":["BaseAdapter.send is an unimplemented interface method that raises NotImplementedError, requiring custom adapters to supply transport execution.","Session.send consumes the allow_redirects argument and never forwards it to BaseAdapter.send keyword arguments.","When BaseAdapter.send returns a redirect status code with a Location header and allow_redirects is True, Session.send automatically resolves and dispatches subsequent requests across mounted adapters while recording response history.","When allow_redirects is False, Session.send populates the next PreparedRequest on response.next without invoking BaseAdapter.send for subsequent hops.","Session.send eagerly consumes unread raw streams returned by BaseAdapter.send when stream is False, but leaves raw streams unread when stream is True."],"goal":"Verify requests 2.34.2 BaseAdapter.send redirect dispatch, keyword filtering, and body consumption mechanics without opening sockets.","kind":"HOW","packages":["pkg:pypi/requests@2.34.2"],"schemaVersion":1,"symbols":["requests.adapters.BaseAdapter","requests.adapters.BaseAdapter.send","requests.Session.send","requests.Session.mount","requests.PreparedRequest","requests.Response"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/requests@2.34.2"],"schemaVersion":1,"symbols":["requests.adapters.BaseAdapter","requests.adapters.BaseAdapter.send","requests.Session.send","requests.Session.mount","requests.PreparedRequest","requests.Response"],"verifierAdapter":"python@1"}
requirements.txt
certifi==2026.2.25
charset-normalizer==3.4.7
idna==3.18
requests==2.34.2
urllib3==2.6.3
test/contract.py
import io
from importlib.metadata import version

import requests
from requests import PreparedRequest, Request, Response, Session
from requests.adapters import BaseAdapter

EXPECTED_VERSION = "2.34.2"


class UnimplementedAdapter(BaseAdapter):
    """Subclass inheriting BaseAdapter.send unchanged."""

    def close(self) -> None:
        pass


class CustomTransportAdapter(BaseAdapter):
    """Socket-free transport adapter tracking calls and parameters."""

    def __init__(self) -> None:
        super().__init__()
        self.calls = []

    def send(
        self,
        request: PreparedRequest,
        stream: bool = False,
        timeout=None,
        verify=True,
        cert=None,
        proxies=None,
        **kwargs,
    ) -> Response:
        self.calls.append(
            {
                "request": request,
                "url": request.url,
                "stream": stream,
                "timeout": timeout,
                "verify": verify,
                "cert": cert,
                "proxies": proxies,
                "kwargs": kwargs,
            }
        )
        response = Response()
        response.request = request
        response.url = request.url

        if request.url == "mock://example.com/start":
            response.status_code = 302
            response.headers["Location"] = "mock://example.org/final"
            response._content = b"redirecting..."
        elif request.url == "mock://example.org/final":
            response.status_code = 200
            response.headers["Content-Type"] = "text/plain; charset=utf-8"
            response._content = b"final landing page body"
        elif request.url == "mock://example.com/stream-data":
            response.status_code = 200
            response.raw = io.BytesIO(b"streaming payload bytes")
        return response

    def close(self) -> None:
        pass


def assert_raises(exc_type, call):
    try:
        call()
    except exc_type as exc:
        return exc
    raise AssertionError(f"Expected {exc_type.__name__} to be raised")


def test_base_adapter_send_abstract() -> None:
    base = BaseAdapter()
    req = Request("GET", "mock://example.com/start").prepare()
    assert isinstance(req, PreparedRequest)

    assert_raises(NotImplementedError, lambda: base.send(req))

    session = Session()
    session.mount("mock://", UnimplementedAdapter())
    assert_raises(NotImplementedError, lambda: session.send(req))
    session.close()


def test_session_redirect_dispatch_and_kwarg_filtering() -> None:
    session = Session()
    adapter = CustomTransportAdapter()
    session.mount("mock://", adapter)
    req = Request("GET", "mock://example.com/start").prepare()

    response = session.send(req, allow_redirects=True)
    assert response.status_code == 200
    assert response.url == "mock://example.org/final"
    assert response.text == "final landing page body"
    assert len(response.history) == 1
    assert response.history[0].status_code == 302
    assert response.history[0].url == "mock://example.com/start"

    # Session.send called adapter.send twice (once for initial, once for redirect hop)
    assert len(adapter.calls) == 2
    assert adapter.calls[0]["url"] == "mock://example.com/start"
    assert adapter.calls[1]["url"] == "mock://example.org/final"

    # allow_redirects is stripped by Session.send and never passed to adapter.send
    assert "allow_redirects" not in adapter.calls[0]["kwargs"]
    assert "allow_redirects" not in adapter.calls[1]["kwargs"]
    session.close()


def test_no_redirect_response_next() -> None:
    session = Session()
    adapter = CustomTransportAdapter()
    session.mount("mock://", adapter)
    req = Request("GET", "mock://example.com/start").prepare()

    response = session.send(req, allow_redirects=False)
    assert response.status_code == 302
    assert len(response.history) == 0
    assert len(adapter.calls) == 1

    # Next request is constructed and stored on response.next without calling adapter.send
    assert response.next is not None
    assert isinstance(response.next, PreparedRequest)
    assert response.next.url == "mock://example.org/final"
    session.close()


def test_stream_body_consumption() -> None:
    session = Session()
    adapter = CustomTransportAdapter()
    session.mount("mock://", adapter)
    stream_req = Request("GET", "mock://example.com/stream-data").prepare()

    # stream=True leaves raw stream unread
    response_stream = session.send(stream_req, stream=True)
    assert response_stream._content_consumed is False
    assert response_stream.raw.read() == b"streaming payload bytes"

    # stream=False eagerly consumes raw stream into content
    response_nostream = session.send(stream_req, stream=False)
    assert response_nostream._content_consumed is True
    assert response_nostream.content == b"streaming payload bytes"
    session.close()


def main() -> None:
    assert version("requests") == EXPECTED_VERSION
    assert requests.__version__ == EXPECTED_VERSION

    test_base_adapter_send_abstract()
    test_session_redirect_dispatch_and_kwarg_filtering()
    test_no_redirect_response_next()
    test_stream_body_consumption()
    print("CONTRACT PASS: requests.adapters.BaseAdapter.send contract verified")


if __name__ == "__main__":
    main()

Ursprungs-Seeder

csx-seed