CodeSampleX

Пример

fastapi 0.141.1: responses.FileResponse

Проверенный пример — pypi fastapi 0.141.1: responses.FileResponse. Контракт выполнен на python 3.12 · linux alpine/x64 · docker и пройден.

sha256:43a65dba51bbc0a6a4f8fa641b87b12afbf38fbee7004a285920d2613e1e73c4

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 pip

Среды запусков проверки

Окружение Контракт Этапы Запуск
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

Кейс

HOW
Цель
verify fastapi.responses.FileResponse in pkg:pypi/fastapi@0.141.1
Пакеты
Символы
  • fastapi.responses.FileResponse
Создан
2026-08-28T04:27:08Z

Контракт

  1. assert FileResponse initializes with a str or PathLike path, auto-detects media_type from file extension, and sets default status code 200
  2. assert FileResponse sets Content-Disposition header with filename parameter and respects content_disposition_type ('attachment' or 'inline')
  3. assert FileResponse streams file contents via ASGI response start and body messages, including Content-Length, ETag, and Last-Modified headers
  4. assert FileResponse supports HTTP Range requests and returns HTTP 206 Partial Content with Content-Range and matching byte slice
  5. assert FileResponse responds to HEAD requests with file metadata headers and an empty response body
  6. assert FileResponse raises RuntimeError when attempting to send a file that does not exist

Файлы

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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# FastAPI FileResponse API Contract Verification

This sample pins `fastapi` 0.141.1 and verifies the behavior and contract of `fastapi.responses.FileResponse`.

The contract verifies:
- Initialization with `str` or `pathlib.Path` objects, auto-detection of `media_type` from file extension, and default HTTP 200 status code.
- Setting of `Content-Disposition` header with `filename` and handling of `content_disposition_type` ('attachment' vs 'inline').
- Streaming file contents across ASGI boundary with appropriate `Content-Length`, `ETag`, and `Last-Modified` headers.
- Support for HTTP `Range` requests returning HTTP 206 Partial Content and `Content-Range` headers.
- HEAD request handling returning status and headers with an empty body.
- Raising `RuntimeError` when attempting to serve a non-existent file.
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 fastapi.responses.FileResponse in pkg:pypi/fastapi@0.141.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/fastapi@0.141.1
Demonstrate these symbols/APIs:
  - fastapi.responses.FileResponse

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:c16a83db205a2fcc6aeee6815b60fd5e37491234680e2531aa452342be28326b","contract":["assert FileResponse initializes with a str or PathLike path, auto-detects media_type from file extension, and sets default status code 200","assert FileResponse sets Content-Disposition header with filename parameter and respects content_disposition_type ('attachment' or 'inline')","assert FileResponse streams file contents via ASGI response start and body messages, including Content-Length, ETag, and Last-Modified headers","assert FileResponse supports HTTP Range requests and returns HTTP 206 Partial Content with Content-Range and matching byte slice","assert FileResponse responds to HEAD requests with file metadata headers and an empty response body","assert FileResponse raises RuntimeError when attempting to send a file that does not exist"],"goal":"verify fastapi.responses.FileResponse in pkg:pypi/fastapi@0.141.1","kind":"HOW","packages":["pkg:pypi/fastapi@0.141.1"],"schemaVersion":1,"symbols":["fastapi.responses.FileResponse"]},"contractCommand":["python3","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/fastapi@0.141.1"],"schemaVersion":1,"subject":"pkg:pypi/fastapi@0.141.1","symbols":["fastapi.responses.FileResponse"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-fastapi-fileresponse"
version = "0.1.0"
dependencies = [
    "fastapi==0.141.1",
]
requirements.txt
annotated-doc==0.0.5
annotated-types==0.8.0
anyio==4.14.2
fastapi==0.141.1
idna==3.19
pydantic==2.13.4
pydantic-core==2.46.4
starlette==1.6.0
typing-extensions==4.16.0
typing-inspection==0.4.4
spec.json
{
  "schemaVersion": 1,
  "goal": "verify fastapi.responses.FileResponse in pkg:pypi/fastapi@0.141.1",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/fastapi@0.141.1"
  ],
  "symbols": [
    "fastapi.responses.FileResponse"
  ]
}
test/contract.py
import asyncio
import os
import pathlib
import tempfile
from fastapi.responses import FileResponse


async def run_asgi(response, scope=None):
    messages = []

    async def send(msg):
        messages.append(msg)

    async def receive():
        return {"type": "http.request"}

    if scope is None:
        scope = {"type": "http", "method": "GET", "headers": []}

    await response(scope, receive, send)
    return messages


def test_initialization_and_media_type():
    with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
        f.write(b'{"status": "ok"}')
        tmp_path = f.name
    try:
        resp = FileResponse(tmp_path, status_code=200)
        assert resp.status_code == 200
        assert resp.media_type == "application/json"
        assert resp.headers["content-type"] == "application/json"

        path_obj = pathlib.Path(tmp_path)
        resp_custom = FileResponse(path_obj, media_type="application/octet-stream")
        assert resp_custom.media_type == "application/octet-stream"
        assert resp_custom.headers["content-type"] == "application/octet-stream"
    finally:
        if os.path.exists(tmp_path):
            os.unlink(tmp_path)


def test_content_disposition_attachment_and_inline():
    with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f:
        f.write(b"sample file payload")
        tmp_path = f.name
    try:
        resp_attachment = FileResponse(
            tmp_path,
            filename="document.txt",
            content_disposition_type="attachment",
        )
        assert resp_attachment.headers["content-disposition"] == 'attachment; filename="document.txt"'

        resp_inline = FileResponse(
            tmp_path,
            filename="preview.txt",
            content_disposition_type="inline",
        )
        assert resp_inline.headers["content-disposition"] == 'inline; filename="preview.txt"'
    finally:
        if os.path.exists(tmp_path):
            os.unlink(tmp_path)


async def test_asgi_streaming_and_headers():
    data = b"Streaming file contents across ASGI boundary"
    with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f:
        f.write(data)
        tmp_path = f.name
    try:
        resp = FileResponse(tmp_path)
        messages = await run_asgi(resp)
        assert len(messages) == 2
        assert messages[0]["type"] == "http.response.start"
        assert messages[0]["status"] == 200
        headers_dict = dict(messages[0]["headers"])
        assert headers_dict[b"content-length"] == str(len(data)).encode("ascii")
        assert b"etag" in headers_dict
        assert b"last-modified" in headers_dict
        assert messages[1]["type"] == "http.response.body"
        assert messages[1]["body"] == data
    finally:
        if os.path.exists(tmp_path):
            os.unlink(tmp_path)


async def test_range_requests():
    data = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    with tempfile.NamedTemporaryFile(suffix=".dat", delete=False) as f:
        f.write(data)
        tmp_path = f.name
    try:
        resp = FileResponse(tmp_path)
        scope = {
            "type": "http",
            "method": "GET",
            "headers": [(b"range", b"bytes=10-19")],
        }
        messages = await run_asgi(resp, scope=scope)
        assert messages[0]["status"] == 206
        headers_dict = dict(messages[0]["headers"])
        assert headers_dict[b"content-range"] == b"bytes 10-19/" + str(len(data)).encode("ascii")
        assert headers_dict[b"content-length"] == b"10"
        assert messages[1]["body"] == b"ABCDEFGHIJ"
    finally:
        if os.path.exists(tmp_path):
            os.unlink(tmp_path)


async def test_head_request():
    data = b"HEAD request body should not be transmitted"
    with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f:
        f.write(data)
        tmp_path = f.name
    try:
        resp = FileResponse(tmp_path)
        scope = {
            "type": "http",
            "method": "HEAD",
            "headers": [],
        }
        messages = await run_asgi(resp, scope=scope)
        assert messages[0]["status"] == 200
        headers_dict = dict(messages[0]["headers"])
        assert headers_dict[b"content-length"] == str(len(data)).encode("ascii")
        assert messages[1]["body"] == b""
    finally:
        if os.path.exists(tmp_path):
            os.unlink(tmp_path)


async def test_nonexistent_file_runtime_error():
    resp = FileResponse("definitely_non_existent_file_xyz_123.txt")
    try:
        await run_asgi(resp)
        assert False, "Should have raised RuntimeError"
    except RuntimeError as exc:
        assert "does not exist" in str(exc)


def main():
    test_initialization_and_media_type()
    test_content_disposition_attachment_and_inline()
    asyncio.run(test_asgi_streaming_and_headers())
    asyncio.run(test_range_requests())
    asyncio.run(test_head_request())
    asyncio.run(test_nonexistent_file_runtime_error())
    print("ALL CONTRACT CHECKS PASSED")


if __name__ == "__main__":
    main()

Исходный сидер

аноним