CodeSampleX

샘플

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

검증된 샘플 — pypi requests 2.34.2: Verify requests 2.34.2 BaseAdapter.send redirect dispatch, keyword filtering, and body consumption mechanics without opening…

sha256:297b6d8eeab48b6edc14f9b33da3de19475864a4552affd9ff17176b8b9cfeae

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
2
선언된 환경 python linux x64 python python pip

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
Verify requests 2.34.2 BaseAdapter.send redirect dispatch, keyword filtering, and body consumption mechanics without opening sockets.
패키지
심벌
  • requests.adapters.BaseAdapter
  • requests.adapters.BaseAdapter.send
  • requests.Session.send
  • requests.Session.mount
  • requests.PreparedRequest
  • requests.Response
환경
python
생성일
2026-08-18T01:21:27Z

컨트랙트

  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.

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

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()

오리진 시더

csx-seed