CodeSampleX

Exemplo

sse-starlette 3.4.8: EventSourceResponse server-sent events stream in Starlette

Amostra verificada para pypi sse-starlette 3.4.8: EventSourceResponse server-sent events stream in Starlette. O contrato rodou em python 3.12 · linux…

sha256:ab34c4a076c7021aaf4e46ec415acbfe75545142e31f8aecf3512d37510d46ed

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado python 3.12 linux 24 · ubuntu · glibc 2.39 x64 python 3.12 python pip 24

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-27

Caso

HOW
Objetivo
EventSourceResponse server-sent events stream in Starlette
Pacotes
Símbolos
  • sse_starlette.sse.EventSourceResponse
Ambiente
python 3.12
Criado
2026-08-27T19:06:55Z

Contrato

  1. assert EventSourceResponse sets media_type to text/event-stream with no-store and keep-alive headers
  2. assert EventSourceResponse streams string and dictionary payloads formatted as SSE events
  3. assert EventSourceResponse streams ServerSentEvent instances with custom event, id, and retry fields
  4. assert ServerSentEvent encodes comment lines, multiline data, and custom separators into bytes
  5. assert EventSourceResponse configures custom ping_interval and exposes default constants

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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: EventSourceResponse server-sent events stream in Starlette
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/sse-starlette@3.4.8
Demonstrate these symbols/APIs:
  - sse_starlette.sse.EventSourceResponse

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:cd0f9f883d039ac44ec50e5474f069db4ebd5ae4865a0734b8a2d9db6abd7bfa","contract":["assert EventSourceResponse sets media_type to text/event-stream with no-store and keep-alive headers","assert EventSourceResponse streams string and dictionary payloads formatted as SSE events","assert EventSourceResponse streams ServerSentEvent instances with custom event, id, and retry fields","assert ServerSentEvent encodes comment lines, multiline data, and custom separators into bytes","assert EventSourceResponse configures custom ping_interval and exposes default constants"],"goal":"EventSourceResponse server-sent events stream in Starlette","kind":"HOW","packages":["pkg:pypi/sse-starlette@3.4.8"],"schemaVersion":1,"symbols":["sse_starlette.sse.EventSourceResponse"]},"contractCommand":["python3","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","packageManagerVersion":"24.0","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/sse-starlette@3.4.8"],"schemaVersion":1,"subject":"pkg:pypi/sse-starlette@3.4.8","symbols":["sse_starlette.sse.EventSourceResponse"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-sse-starlette"
version = "0.1.0"
dependencies = [
    "sse-starlette==3.4.8",
    "starlette>=0.37.0",
    "anyio>=4.0.0",
    "sniffio>=1.3.0",
    "typing-extensions>=4.8.0",
    "idna>=3.0",
    "httpx>=0.27.0",
    "httpcore>=1.0.0",
    "certifi",
    "h11>=0.14.0",
]
requirements.txt
sse-starlette==3.4.8
starlette>=0.37.0
anyio>=4.0.0
sniffio>=1.3.0
typing-extensions>=4.8.0
idna>=3.0
httpx>=0.27.0
httpcore>=1.0.0
certifi
h11>=0.14.0
spec.json
{
  "schemaVersion": 1,
  "goal": "EventSourceResponse server-sent events stream in Starlette",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/sse-starlette@3.4.8"
  ],
  "symbols": [
    "sse_starlette.sse.EventSourceResponse"
  ]
}
test/contract.py
import asyncio
from sse_starlette.sse import EventSourceResponse, ServerSentEvent
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.testclient import TestClient


def test_event_source_response_headers():
    response = EventSourceResponse(None, status_code=200, headers={"X-Custom-Header": "SSE-Stream"})
    assert response.media_type == "text/event-stream"
    assert response.status_code == 200
    assert response.headers["content-type"] == "text/event-stream; charset=utf-8"
    assert response.headers["cache-control"] == "no-store"
    assert response.headers["connection"] == "keep-alive"
    assert response.headers["x-custom-header"] == "SSE-Stream"
    assert response.headers["x-accel-buffering"] == "no"


def test_event_source_response_stream_payloads():
    async def endpoint(request):
        async def event_generator():
            yield "simple-text"
            yield {"data": "json-val", "event": "update", "id": "msg-1"}
            yield ServerSentEvent(data="sse-data", event="custom", id="msg-2", retry=3000)
        return EventSourceResponse(event_generator(), ping=None)

    app = Starlette(routes=[Route("/events", endpoint)])
    client = TestClient(app)
    res = client.get("/events")

    assert res.status_code == 200
    assert res.headers["content-type"] == "text/event-stream; charset=utf-8"
    assert "data: simple-text" in res.text
    assert "event: update" in res.text
    assert "data: json-val" in res.text
    assert "id: msg-1" in res.text
    assert "event: custom" in res.text
    assert "data: sse-data" in res.text
    assert "id: msg-2" in res.text
    assert "retry: 3000" in res.text


def test_serversentevent_encoding():
    s1 = ServerSentEvent(data="hello world")
    assert s1.encode() == b"data: hello world\r\n\r\n"

    s2 = ServerSentEvent(data="line1\nline2", event="alert", id="42", retry=5000, comment="heartbeat")
    encoded = s2.encode().decode("utf-8")
    assert ": heartbeat\r\n" in encoded
    assert "id: 42\r\n" in encoded
    assert "event: alert\r\n" in encoded
    assert "data: line1\r\ndata: line2\r\n" in encoded
    assert "retry: 5000\r\n" in encoded

    s3 = ServerSentEvent(data="custom-sep", sep="\n")
    assert s3.encode() == b"data: custom-sep\n\n"


def test_event_source_response_ping_and_defaults():
    resp = EventSourceResponse(None, ping=30)
    assert resp.ping_interval == 30
    assert resp.DEFAULT_PING_INTERVAL == 15
    assert resp.DEFAULT_SEPARATOR == "\r\n"


def main():
    test_event_source_response_headers()
    test_event_source_response_stream_payloads()
    test_serversentevent_encoding()
    test_event_source_response_ping_and_defaults()
    print("All contract assertions passed.")


if __name__ == "__main__":
    main()

Seeder de origem

anônimo