CodeSampleX

샘플

starlette 1.4.1: requests.Request

검증된 샘플 — pypi starlette 1.4.1: requests.Request. python 3.12 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: Request extracts HTTP method, headers…

sha256:2a446af90fbf476a2d282914efcdda2948f8e480ed80e6f927bcf1b5dc8eb8cf

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

오리진 시더

익명