CodeSampleX

示例

starlette 1.4.1: requests.Request

已验证示例 — pypi starlette 1.4.1: requests.Request. contract 在 python 3.12 · linux debian/x64 · docker 上运行并通过: Request extracts HTTP method, headers, cookies…

sha256:2a446af90fbf476a2d282914efcdda2948f8e480ed80e6f927bcf1b5dc8eb8cf

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

执行证据

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

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

验证运行环境

环境 契约 阶段 运行日期
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-03

案例

HOW
目标
verify starlette.requests.Request in pkg:pypi/starlette@1.4.1
包
符号
  • starlette.requests.Request
环境
python
创建时间
2026-09-03T15:54:11Z

契约

  1. Request extracts HTTP method, headers, cookies, and query parameters from ASGI connection scope
  2. Request reads and parses JSON payload asynchronously from request body stream
  3. Request provides client connection details and request-scoped state storage

文件

  • PROMPT.md
  • csx.json
  • 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.requests.Request in pkg:pypi/starlette@1.4.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/starlette@1.4.1
Demonstrate these symbols/APIs:
  - starlette.requests.Request

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:4e4ae1c2c80549337252e65996608e0cc4ff187c4255efbbeb0adbb3dda3150a","contract":["Request extracts HTTP method, headers, cookies, and query parameters from ASGI connection scope","Request reads and parses JSON payload asynchronously from request body stream","Request provides client connection details and request-scoped state storage"],"goal":"verify starlette.requests.Request in pkg:pypi/starlette@1.4.1","kind":"HOW","packages":["pkg:pypi/starlette@1.4.1"],"schemaVersion":1,"symbols":["starlette.requests.Request"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/starlette@1.4.1"],"schemaVersion":1,"subject":"pkg:pypi/starlette@1.4.1","symbols":["starlette.requests.Request"],"verifierAdapter":"python@1"}
requirements.txt
anyio==4.14.2
idna==3.19
starlette==1.4.1
typing-extensions==4.16.0
sample.py
"""Sample demonstrating HTTP request parsing, payload processing, and state handling with Starlette Request."""

from typing import Any, Dict
from starlette.requests import Request


def get_request_metadata(request: Request) -> Dict[str, Any]:
    """Extract connection metadata, headers, cookies, and query parameters from Request."""
    return {
        "method": request.method,
        "path": request.url.path,
        "query_params": dict(request.query_params),
        "headers": {
            "content_type": request.headers.get("content-type"),
            "request_id": request.headers.get("x-request-id"),
        },
        "cookies": dict(request.cookies),
    }


async def read_request_payload(request: Request) -> Dict[str, Any]:
    """Read raw payload bytes and parse JSON data asynchronously from Request."""
    body_bytes = await request.body()
    json_data = await request.json()
    return {
        "byte_count": len(body_bytes),
        "parsed": json_data,
    }


def manage_request_state(request: Request, key: str, value: Any) -> Any:
    """Store and retrieve arbitrary state attributes on request.state."""
    setattr(request.state, key, value)
    return getattr(request.state, key)
spec.json
{
  "schemaVersion": 1,
  "goal": "verify starlette.requests.Request in pkg:pypi/starlette@1.4.1",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/starlette@1.4.1"
  ],
  "symbols": [
    "starlette.requests.Request"
  ]
}
test/contract.py
"""Contract verification tests for starlette.requests.Request."""

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

# 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 sample import get_request_metadata, read_request_payload, manage_request_state


def create_asgi_http_scope(
    method: str = "GET",
    path: str = "/",
    query_string: bytes = b"",
    headers: Optional[List[Tuple[bytes, bytes]]] = None,
    client: Optional[Tuple[str, int]] = None,
) -> Dict[str, Any]:
    """Construct an ASGI HTTP connection scope dictionary for offline testing."""
    return {
        "type": "http",
        "http_version": "1.1",
        "method": method,
        "scheme": "http",
        "server": ("127.0.0.1", 80),
        "path": path,
        "raw_path": path.encode("latin-1"),
        "query_string": query_string,
        "headers": headers or [],
        "client": client or ("127.0.0.1", 50000),
    }


def test_request_metadata_extraction() -> None:
    """Assertion 1: Request extracts HTTP method, headers, cookies, and query parameters from ASGI connection scope."""
    scope = create_asgi_http_scope(
        method="GET",
        path="/api/search",
        query_string=b"q=starlette&page=1",
        headers=[
            (b"content-type", b"application/json"),
            (b"x-request-id", b"req-abc-123"),
            (b"cookie", b"session_id=sess-token-456"),
        ],
    )
    request = Request(scope)

    metadata = get_request_metadata(request)
    assert metadata["method"] == "GET"
    assert metadata["path"] == "/api/search"
    assert metadata["query_params"] == {"q": "starlette", "page": "1"}
    assert metadata["headers"]["content_type"] == "application/json"
    assert metadata["headers"]["request_id"] == "req-abc-123"
    assert metadata["cookies"] == {"session_id": "sess-token-456"}


def test_request_payload_and_json_parsing() -> None:
    """Assertion 2: Request reads and parses JSON payload asynchronously from request body stream."""
    payload = {"symbol": "Request", "status": "active", "items": [1, 2, 3]}
    payload_bytes = json.dumps(payload).encode("utf-8")

    async def receive() -> Dict[str, Any]:
        return {
            "type": "http.request",
            "body": payload_bytes,
            "more_body": False,
        }

    scope = create_asgi_http_scope(
        method="POST",
        path="/api/submit",
        headers=[(b"content-type", b"application/json")],
    )
    request = Request(scope, receive=receive)

    async def run_async_test() -> None:
        result = await read_request_payload(request)
        assert result["byte_count"] == len(payload_bytes)
        assert result["parsed"] == payload
        assert result["parsed"]["symbol"] == "Request"

    asyncio.run(run_async_test())


def test_request_client_and_state() -> None:
    """Assertion 3: Request provides client connection details and request-scoped state storage."""
    client_address = ("127.0.0.1", 54321)
    scope = create_asgi_http_scope(
        method="GET",
        path="/api/client",
        client=client_address,
    )
    request = Request(scope)

    assert request.client is not None
    assert request.client.host == "127.0.0.1"
    assert request.client.port == 54321

    stored_value = manage_request_state(request, "tenant_id", "tenant-001")
    assert stored_value == "tenant-001"
    assert request.state.tenant_id == "tenant-001"


def main() -> None:
    test_request_metadata_extraction()
    test_request_payload_and_json_parsing()
    test_request_client_and_state()
    print("Starlette Request contract verification passed.")


if __name__ == "__main__":
    main()

原始种子者

匿名