CodeSampleX

Ejemplo

starlette 1.6.0: applications.Starlette, routing.Route, requests.Request

Muestra verificada para pypi starlette 1.6.0: applications.Starlette, routing.Route, requests.Request. El contrato se ejecutó en python 3.12 · linux…

sha256:448b96fdad14304698392075a4375d830f81766d7f6951856b89252af7b04662

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado python linux 24 · ubuntu · glibc 2.39 x64 python python pip

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
verify pkg:pypi/starlette@1.6.0
Paquetes
Símbolos
  • starlette.applications.Starlette
  • starlette.routing.Route
  • starlette.requests.Request
  • starlette.responses.JSONResponse
  • starlette.exceptions.HTTPException
Entorno
python
Creado
2026-08-28T06:39:14Z

Contrato

  1. Starlette routes HTTP GET requests to route handlers and returns JSONResponse payloads
  2. Starlette parses JSON request bodies and path parameters via Request and returns JSONResponse
  3. Starlette handles HTTPException via custom exception handlers and returns appropriate status codes

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 pkg:pypi/starlette@1.6.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/starlette@1.6.0

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:af884a039443ce429a231ee456a9b1b3c5b864d3b1c0d6b9f791ad23f2f534f4","contract":["Starlette routes HTTP GET requests to route handlers and returns JSONResponse payloads","Starlette parses JSON request bodies and path parameters via Request and returns JSONResponse","Starlette handles HTTPException via custom exception handlers and returns appropriate status codes"],"goal":"verify pkg:pypi/starlette@1.6.0","kind":"HOW","packages":["pkg:pypi/starlette@1.6.0"],"schemaVersion":1,"symbols":["starlette.applications.Starlette","starlette.routing.Route","starlette.requests.Request","starlette.responses.JSONResponse","starlette.exceptions.HTTPException"]},"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.6.0"],"schemaVersion":1,"subject":"pkg:pypi/starlette@1.6.0","symbols":["starlette.applications.Starlette","starlette.routing.Route","starlette.requests.Request","starlette.responses.JSONResponse","starlette.exceptions.HTTPException"],"verifierAdapter":"python@1"}
requirements.txt
anyio==4.14.2
idna==3.19
starlette==1.6.0
typing-extensions==4.16.0
sample.py
"""Sample demonstrating HTTP request routing and JSON response handling with Starlette."""

from typing import Any, Dict
from starlette.applications import Starlette
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route


async def get_health(request: Request) -> JSONResponse:
    """Return health check status."""
    return JSONResponse({"status": "ok", "service": "api"})


async def get_user_profile(request: Request) -> JSONResponse:
    """Return user details based on path parameter."""
    user_id = request.path_params.get("user_id")
    if user_id == "unknown":
        raise HTTPException(status_code=404, detail="User not found")
    return JSONResponse({"user_id": user_id, "active": True})


async def create_item(request: Request) -> JSONResponse:
    """Process incoming JSON payload and return created item."""
    payload: Dict[str, Any] = await request.json()
    name = payload.get("name", "")
    quantity = payload.get("quantity", 0)
    return JSONResponse(
        {"item": {"name": name, "quantity": quantity}, "created": True},
        status_code=201,
    )


async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
    """Handle HTTPException by returning structured JSON error."""
    return JSONResponse({"error": exc.detail}, status_code=exc.status_code)


def create_app() -> Starlette:
    """Create and configure Starlette application with routes and exception handlers."""
    routes = [
        Route("/health", get_health, methods=["GET"]),
        Route("/users/{user_id}", get_user_profile, methods=["GET"]),
        Route("/items", create_item, methods=["POST"]),
    ]
    exception_handlers = {
        HTTPException: http_exception_handler,
    }
    return Starlette(routes=routes, exception_handlers=exception_handlers)


if __name__ == "__main__":
    app = create_app()
    print("Starlette application configured with routes and exception handlers.")
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:pypi/starlette@1.6.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/starlette@1.6.0"
  ]
}
test/contract.py
"""Contract verification tests for Starlette application routing, request handling, and exception handling."""

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.applications import Starlette
from sample import create_app


async def invoke_asgi(
    app: Starlette,
    method: str,
    path: str,
    body: bytes = b"",
    headers: Optional[List[Tuple[bytes, bytes]]] = None,
) -> Tuple[int, Dict[bytes, bytes], bytes]:
    """Helper to invoke ASGI application offline without external networking dependencies."""
    if headers is None:
        headers = [(b"content-type", b"application/json")]

    scope = {
        "type": "http",
        "http_version": "1.1",
        "method": method,
        "path": path,
        "raw_path": path.encode("latin-1"),
        "query_string": b"",
        "headers": headers,
    }

    sent_messages = []

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

    async def send(message: Dict[str, Any]) -> None:
        sent_messages.append(message)

    await app(scope, receive, send)

    status_code = 0
    resp_headers = {}
    response_body = b""

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

    return status_code, resp_headers, response_body


def test_get_routing_and_json_response() -> None:
    """Assertion 1: Starlette routes HTTP GET requests to route handlers and returns JSONResponse payloads."""
    app = create_app()

    async def run_test() -> None:
        status, headers, body = await invoke_asgi(app, "GET", "/health")
        assert status == 200, f"Expected 200, got {status}"
        assert b"application/json" in headers.get(b"content-type", b"")
        data = json.loads(body.decode("utf-8"))
        assert data == {"status": "ok", "service": "api"}

    asyncio.run(run_test())


def test_request_json_body_and_path_params() -> None:
    """Assertion 2: Starlette parses JSON request bodies and path parameters via Request and returns JSONResponse."""
    app = create_app()

    async def run_test() -> None:
        # Test path parameter routing
        status, headers, body = await invoke_asgi(app, "GET", "/users/usr_12345")
        assert status == 200, f"Expected 200, got {status}"
        data = json.loads(body.decode("utf-8"))
        assert data == {"user_id": "usr_12345", "active": True}

        # Test POST request with JSON body
        payload = json.dumps({"name": "widget", "quantity": 42}).encode("utf-8")
        status, headers, body = await invoke_asgi(app, "POST", "/items", body=payload)
        assert status == 201, f"Expected 201, got {status}"
        data = json.loads(body.decode("utf-8"))
        assert data == {"item": {"name": "widget", "quantity": 42}, "created": True}

    asyncio.run(run_test())


def test_http_exception_handling() -> None:
    """Assertion 3: Starlette handles HTTPException via custom exception handlers and returns appropriate status codes."""
    app = create_app()

    async def run_test() -> None:
        status, headers, body = await invoke_asgi(app, "GET", "/users/unknown")
        assert status == 404, f"Expected 404, got {status}"
        assert b"application/json" in headers.get(b"content-type", b"")
        data = json.loads(body.decode("utf-8"))
        assert data == {"error": "User not found"}

    asyncio.run(run_test())


def main() -> None:
    test_get_routing_and_json_response()
    test_request_json_body_and_path_params()
    test_http_exception_handling()
    print("Starlette contract verification passed.")


if __name__ == "__main__":
    main()

Seeder de origen

anónimo