CodeSampleX

示例

starlette 1.6.0: types.Receive

已验证示例 — pypi starlette 1.6.0: types.Receive. contract 在 python 3.12 · linux alpine/x64 · docker 上运行并通过: assert Receive callable consumes streamed HTTP…

sha256:99b913ac5905ddb4cacf56c4c944587fea97d802bbe1248b6185f736d6a94d61

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 pip

验证运行环境

环境 契约 阶段 运行日期
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962…
2026-08-28

案例

HOW
目标
verify starlette.types.Receive in pkg:pypi/starlette@1.6.0
包
符号
  • starlette.types.Receive
创建时间
2026-08-28T06:47:34Z

契约

  1. assert Receive callable consumes streamed HTTP request body chunks until more_body is False
  2. assert Receive callable cleanly handles http.disconnect message during body consumption
  3. assert Starlette Request resolves complete body when initialized with custom Receive callable
  4. assert BufferedReceiveMiddleware wraps Receive callable and forwards ASGI messages downstream
  5. assert starlette.types.Receive type annotations match ASGI 3.0 specification

文件

  • PROMPT.md
  • csx.json
  • pyproject.toml
  • requirements.txt
  • sample.py
  • spec.json
  • test/contract.py

下载源代码构件 (tar.gz)

源代码

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify starlette.types.Receive in pkg:pypi/starlette@1.6.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/starlette@1.6.0
Demonstrate these symbols/APIs:
  - starlette.types.Receive

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:eb59b072b44dcd327458946b99d7c7d7de995076a96b12e8c1125ddb42c6464d","contract":["assert Receive callable consumes streamed HTTP request body chunks until more_body is False","assert Receive callable cleanly handles http.disconnect message during body consumption","assert Starlette Request resolves complete body when initialized with custom Receive callable","assert BufferedReceiveMiddleware wraps Receive callable and forwards ASGI messages downstream","assert starlette.types.Receive type annotations match ASGI 3.0 specification"],"goal":"verify starlette.types.Receive in pkg:pypi/starlette@1.6.0","kind":"HOW","packages":["pkg:pypi/starlette@1.6.0"],"schemaVersion":1,"symbols":["starlette.types.Receive"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/starlette@1.6.0"],"schemaVersion":1,"subject":"pkg:pypi/starlette@1.6.0","symbols":["starlette.types.Receive"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-starlette-receive"
version = "0.1.0"
dependencies = [
    "starlette==1.6.0",
    "anyio>=3.4.0",
    "typing-extensions>=4.0.0",
]
requirements.txt
anyio==4.14.2
idna==3.19
starlette==1.6.0
typing-extensions==4.16.0
sample.py
"""Sample demonstrating custom ASGI body consumption and middleware using starlette.types.Receive."""

from typing import List
from starlette.types import Receive, Scope, Send, Message
from starlette.responses import JSONResponse


class StreamBodyReceiver:
    """Consumes incoming request body chunks from an ASGI Receive callable."""

    def __init__(self, receive: Receive) -> None:
        self.receive = receive

    async def read_full_body(self) -> bytes:
        chunks: List[bytes] = []
        while True:
            message: Message = await self.receive()
            msg_type = message.get("type")
            if msg_type == "http.request":
                chunk = message.get("body", b"")
                if chunk:
                    chunks.append(chunk)
                if not message.get("more_body", False):
                    break
            elif msg_type == "http.disconnect":
                break
        return b"".join(chunks)


class BufferedReceiveMiddleware:
    """ASGI middleware that wraps Receive to inspect and pass along request bodies."""

    def __init__(self, app) -> None:
        self.app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope.get("type") != "http":
            await self.app(scope, receive, send)
            return

        received_log: List[str] = []

        async def buffered_receive() -> Message:
            msg = await receive()
            if msg.get("type") == "http.request":
                body_len = len(msg.get("body", b""))
                received_log.append(f"chunk:{body_len}")
            elif msg.get("type") == "http.disconnect":
                received_log.append("disconnect")
            return msg

        scope["app.buffered_log"] = received_log
        await self.app(scope, buffered_receive, send)


async def raw_asgi_app(scope: Scope, receive: Receive, send: Send) -> None:
    """Raw ASGI application directly consuming Receive callable."""
    if scope.get("type") != "http":
        return

    receiver = StreamBodyReceiver(receive)
    body = await receiver.read_full_body()

    response = JSONResponse(
        {
            "received_bytes": len(body),
            "content": body.decode("utf-8") if body else "",
            "log": scope.get("app.buffered_log", []),
        }
    )
    await response(scope, receive, send)
spec.json
{
  "schemaVersion": 1,
  "goal": "verify starlette.types.Receive in pkg:pypi/starlette@1.6.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/starlette@1.6.0"
  ],
  "symbols": [
    "starlette.types.Receive"
  ]
}
test/contract.py
"""Contract verification tests for starlette.types.Receive."""

import asyncio
import json
import os
import sys
from typing import Any, Dict, List

# Ensure project root is on sys.path for local module imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from starlette.requests import Request
from starlette.types import Receive, Scope, Send, Message
from sample import StreamBodyReceiver, BufferedReceiveMiddleware, raw_asgi_app


def test_receive_streamed_chunks() -> None:
    """Assertion 1: assert Receive callable consumes streamed HTTP request body chunks until more_body is False"""
    chunk_list = [b"part1-", b"part2-", b"part3"]
    chunk_index = 0

    async def mock_receive() -> Message:
        nonlocal chunk_index
        if chunk_index < len(chunk_list):
            chunk = chunk_list[chunk_index]
            chunk_index += 1
            is_last = chunk_index >= len(chunk_list)
            return {"type": "http.request", "body": chunk, "more_body": not is_last}
        return {"type": "http.request", "body": b"", "more_body": False}

    async def run() -> None:
        receiver = StreamBodyReceiver(mock_receive)
        full_body = await receiver.read_full_body()
        assert full_body == b"part1-part2-part3", f"Unexpected body: {full_body}"
        assert chunk_index == 3, f"Expected 3 chunks read, got {chunk_index}"

    asyncio.run(run())


def test_receive_disconnect_handling() -> None:
    """Assertion 2: assert Receive callable cleanly handles http.disconnect message during body consumption"""
    calls = 0

    async def disconnect_receive() -> Message:
        nonlocal calls
        calls += 1
        if calls == 1:
            return {"type": "http.request", "body": b"initial_chunk", "more_body": True}
        return {"type": "http.disconnect"}

    async def run() -> None:
        receiver = StreamBodyReceiver(disconnect_receive)
        result = await receiver.read_full_body()
        assert result == b"initial_chunk", f"Unexpected body on disconnect: {result}"
        assert calls == 2

    asyncio.run(run())


def test_starlette_request_with_custom_receive() -> None:
    """Assertion 3: assert Starlette Request resolves complete body when initialized with custom Receive callable"""
    scope: Scope = {
        "type": "http",
        "http_version": "1.1",
        "method": "POST",
        "path": "/submit",
        "raw_path": b"/submit",
        "query_string": b"",
        "headers": [(b"content-type", b"text/plain")],
    }

    message_queue = [
        {"type": "http.request", "body": b"hello ", "more_body": True},
        {"type": "http.request", "body": b"world", "more_body": False},
    ]

    async def custom_receive() -> Message:
        if message_queue:
            return message_queue.pop(0)
        return {"type": "http.request", "body": b"", "more_body": False}

    async def run() -> None:
        req = Request(scope, receive=custom_receive)
        body = await req.body()
        assert body == b"hello world", f"Unexpected request body: {body}"

    asyncio.run(run())


def test_buffered_receive_middleware() -> None:
    """Assertion 4: assert BufferedReceiveMiddleware wraps Receive callable and forwards ASGI messages downstream"""
    scope: Scope = {
        "type": "http",
        "http_version": "1.1",
        "method": "POST",
        "path": "/test",
        "raw_path": b"/test",
        "query_string": b"",
        "headers": [],
    }

    sent_messages: List[Message] = []

    async def mock_send(msg: Message) -> None:
        sent_messages.append(msg)

    raw_chunks = [
        {"type": "http.request", "body": b"payload-chunk-1", "more_body": True},
        {"type": "http.request", "body": b"-and-chunk-2", "more_body": False},
    ]

    async def original_receive() -> Message:
        if raw_chunks:
            return raw_chunks.pop(0)
        return {"type": "http.request", "body": b"", "more_body": False}

    async def run() -> None:
        app = BufferedReceiveMiddleware(raw_asgi_app)
        await app(scope, original_receive, mock_send)

        status_code = 0
        response_body = b""
        for msg in sent_messages:
            if msg["type"] == "http.response.start":
                status_code = msg["status"]
            elif msg["type"] == "http.response.body":
                response_body += msg.get("body", b"")

        assert status_code == 200, f"Expected 200, got {status_code}"
        data = json.loads(response_body.decode("utf-8"))
        assert data["received_bytes"] == len(b"payload-chunk-1-and-chunk-2")
        assert data["content"] == "payload-chunk-1-and-chunk-2"
        assert data["log"] == ["chunk:15", "chunk:12"]

    asyncio.run(run())


def test_receive_type_annotation_contract() -> None:
    """Assertion 5: assert starlette.types.Receive type annotations match ASGI 3.0 specification"""
    async def valid_receive_impl() -> Message:
        return {"type": "http.request", "body": b"", "more_body": False}

    def accepts_receive_target(fn: Receive) -> bool:
        return callable(fn)

    assert accepts_receive_target(valid_receive_impl) is True
    assert Receive is not None


def main() -> None:
    test_receive_streamed_chunks()
    test_receive_disconnect_handling()
    test_starlette_request_with_custom_receive()
    test_buffered_receive_middleware()
    test_receive_type_annotation_contract()
    print("Starlette Receive contract verification passed.")


if __name__ == "__main__":
    main()

原始种子者

匿名