CodeSampleX

Exemplo

starlette 1.4.1: Execute background tasks after HTTP response completion using BackgroundTask and BackgroundTasks in Starlette

Amostra verificada para pypi starlette 1.4.1: Execute background tasks after HTTP response completion using BackgroundTask and BackgroundTasks in Starlette.…

sha256:55d2facdfcd88515c6cfac1cf9141fb727c6cdbdfdec956f4ac79d02d0e7233d

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 linux 24 · ubuntu · glibc 2.39 x64 python python pip

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-28

Caso

HOW
Objetivo
Execute background tasks after HTTP response completion using BackgroundTask and BackgroundTasks in Starlette
Pacotes
Símbolos
  • starlette.background.BackgroundTask
  • starlette.background.BackgroundTasks
Ambiente
python
Criado
2026-08-28T04:16:58Z

Contrato

  1. BackgroundTask executes a background callable after the HTTP response completes
  2. BackgroundTasks executes multiple chained synchronous and asynchronous tasks after the HTTP response completes

Arquivos

  • PROMPT.md
  • csx.json
  • requirements.txt
  • sample.py
  • 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: Execute background tasks after HTTP response completion using BackgroundTask and BackgroundTasks in Starlette
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/starlette@1.4.1
Demonstrate these symbols/APIs:
  - starlette.background.BackgroundTask
  - starlette.background.BackgroundTasks

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:ca239d78e2befb5d4f605dffd809b2bebd8401a78bab3cd597ca86646e9a305b","contract":["BackgroundTask executes a background callable after the HTTP response completes","BackgroundTasks executes multiple chained synchronous and asynchronous tasks after the HTTP response completes"],"goal":"Execute background tasks after HTTP response completion using BackgroundTask and BackgroundTasks in Starlette","kind":"HOW","packages":["pkg:pypi/starlette@1.4.1"],"schemaVersion":1,"symbols":["starlette.background.BackgroundTask","starlette.background.BackgroundTasks"]},"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.background.BackgroundTask","starlette.background.BackgroundTasks"],"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 background task execution with BackgroundTask and BackgroundTasks in Starlette."""

from typing import List
from starlette.applications import Starlette
from starlette.background import BackgroundTask, BackgroundTasks
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route

# In-memory event log for demonstrated background task completions
EVENT_LOG: List[str] = []


def record_sync_event(event_name: str) -> None:
    """Record a synchronous background task event."""
    EVENT_LOG.append(f"sync:{event_name}")


async def record_async_event(event_name: str) -> None:
    """Record an asynchronous background task event."""
    EVENT_LOG.append(f"async:{event_name}")


async def single_task_endpoint(request: Request) -> JSONResponse:
    """Endpoint using a single BackgroundTask attached to JSONResponse."""
    task = BackgroundTask(record_sync_event, "task_completed")
    return JSONResponse({"status": "accepted", "task": "single"}, background=task)


async def multiple_tasks_endpoint(request: Request) -> JSONResponse:
    """Endpoint using BackgroundTasks to chain multiple background tasks."""
    tasks = BackgroundTasks()
    tasks.add_task(record_sync_event, "first_task")
    tasks.add_task(record_async_event, "second_task")
    return JSONResponse({"status": "accepted", "tasks": "multiple"}, background=tasks)


def create_app() -> Starlette:
    """Create and configure Starlette application with background task routes."""
    routes = [
        Route("/single-task", single_task_endpoint, methods=["POST"]),
        Route("/multiple-tasks", multiple_tasks_endpoint, methods=["POST"]),
    ]
    return Starlette(routes=routes)


if __name__ == "__main__":
    app = create_app()
    print("Starlette application configured with BackgroundTask and BackgroundTasks routes.")
spec.json
{
  "schemaVersion": 1,
  "goal": "Execute background tasks after HTTP response completion using BackgroundTask and BackgroundTasks in Starlette",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/starlette@1.4.1"
  ],
  "symbols": [
    "starlette.background.BackgroundTask",
    "starlette.background.BackgroundTasks"
  ]
}
test/contract.py
"""Contract verification tests for Starlette BackgroundTask and BackgroundTasks execution."""

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 EVENT_LOG, 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 and trigger background tasks."""
    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_single_background_task() -> None:
    """Assertion 1: BackgroundTask executes a background callable after the HTTP response completes."""
    EVENT_LOG.clear()
    app = create_app()

    async def run_test() -> None:
        status, headers, body = await invoke_asgi(app, "POST", "/single-task")
        assert status == 200, f"Expected 200, got {status}"
        data = json.loads(body.decode("utf-8"))
        assert data == {"status": "accepted", "task": "single"}
        assert EVENT_LOG == ["sync:task_completed"], f"Unexpected EVENT_LOG: {EVENT_LOG}"

    asyncio.run(run_test())


def test_multiple_background_tasks() -> None:
    """Assertion 2: BackgroundTasks executes multiple chained synchronous and asynchronous tasks after the HTTP response completes."""
    EVENT_LOG.clear()
    app = create_app()

    async def run_test() -> None:
        status, headers, body = await invoke_asgi(app, "POST", "/multiple-tasks")
        assert status == 200, f"Expected 200, got {status}"
        data = json.loads(body.decode("utf-8"))
        assert data == {"status": "accepted", "tasks": "multiple"}
        assert EVENT_LOG == ["sync:first_task", "async:second_task"], f"Unexpected EVENT_LOG: {EVENT_LOG}"

    asyncio.run(run_test())


def main() -> None:
    test_single_background_task()
    test_multiple_background_tasks()
    print("Starlette BackgroundTasks contract verification passed.")


if __name__ == "__main__":
    main()

Seeder de origem

anônimo