GitHub

server_response

API reference for server_response.

HTTP server responses (Effect's HttpServerResponse).

A response is an immutable value: status, headers, cookies and a body (an HttpBody). Build one with text, json, stream, empty, redirect... and refine it with its methods, each giving a new response::

response.text("created", status=201).set_header("x-request-id", rid)

A body with a content type or length sets content-type / content-length when the response is made (an explicit header given with set_header wins over the body's).

Re-exports

Types

TypeDefinitionDescription
CookieEntrytype CookieEntry = tuple[str, str] | tuple[str, str, CookieOptionsInput]

Classes

Functions

is_http_server_response

is_http_server_response(value) -> bool
ParameterTypeDescription
valueobject

Returns bool

def is_http_server_response(value: object) -> bool:
    return isinstance(value, HttpServerResponse)

empty

empty(**options) -> HttpServerResponse

No body; 204 unless status says otherwise.

ParameterTypeDescription
optionsUnpack[Options] = {}

Returns HttpServerResponse

def empty(**options: Unpack[Options]) -> HttpServerResponse:
    """No body; ``204`` unless ``status`` says otherwise."""
    return _make(options, 204, _headers(options), None)

redirect

redirect(location, **options) -> HttpServerResponse

A location redirect; 302 unless status says otherwise.

ParameterTypeDescription
locationstr
optionsUnpack[Options] = {}

Returns HttpServerResponse

def redirect(location: str, **options: Unpack[Options]) -> HttpServerResponse:
    """A ``location`` redirect; ``302`` unless ``status`` says otherwise."""
    headers = Headers({"location": location})
    given = options.get("headers")
    if given is not None:
        headers = headers.merge(headers_from_input(given))
    return _make(options, 302, headers, None)

bytes_

bytes_(body, **options) -> HttpServerResponse

Bytes, application/octet-stream by default (Effect's uint8Array).

ParameterTypeDescription
bodybytes
optionsUnpack[ContentTypeOptions] = {}

Returns HttpServerResponse

def bytes_(body: bytes, **options: Unpack[ContentTypeOptions]) -> HttpServerResponse:
    """Bytes, ``application/octet-stream`` by default (Effect's
    ``uint8Array``)."""
    headers = _headers(options)
    return _make(options, 200, headers, _body.bytes_(body, _content_type(options, headers)))

text

text(body, **options) -> HttpServerResponse

UTF-8 text, text/plain by default.

ParameterTypeDescription
bodystr
optionsUnpack[ContentTypeOptions] = {}

Returns HttpServerResponse

def text(body: str, **options: Unpack[ContentTypeOptions]) -> HttpServerResponse:
    """UTF-8 text, ``text/plain`` by default."""
    headers = _headers(options)
    return _make(options, 200, headers, _body.text(body, _content_type(options, headers)))

html

html(body, **options) -> HttpServerResponse

body as text/html.

ParameterTypeDescription
bodystr
optionsUnpack[Options] = {}

Returns HttpServerResponse

def html(body: str, **options: Unpack[Options]) -> HttpServerResponse:
    """``body`` as ``text/html``."""
    return text(body, **options, content_type="text/html")

html_template

html_template[EE = Never, RR = Never](strings, *args) -> Effect[HttpServerResponse, EE, RR]

The template's text as text/html (Effect's tagged html). Values are not HTML-escaped (as in Effect); escape text that isn't yours with html.escape.

ParameterTypeDescription
stringsSequence[str]
args_template.Interpolated[EE, RR] = ()

Returns Effect[HttpServerResponse, EE, RR]

def html_template[EE = Never, RR = Never](
    strings: Sequence[str], *args: _template.Interpolated[EE, RR]
) -> Effect[HttpServerResponse, EE, RR]:
    """The template's text as ``text/html`` (Effect's tagged ``html``).
    Values are not HTML-escaped (as in Effect); escape text that isn't yours
    with ``html.escape``."""
    return _template.make(strings, *args).map(html)

html_stream

html_stream[EE = Never, RR = Never](strings, *args) -> HttpServerResponse

The template streamed as text/html, each part as it is known. Values are not HTML-escaped (as in Effect).

ParameterTypeDescription
stringsSequence[str]
args_template.InterpolatedWithStream[EE, RR] = ()

Returns HttpServerResponse

def html_stream[EE = Never, RR = Never](
    strings: Sequence[str], *args: _template.InterpolatedWithStream[EE, RR]
) -> HttpServerResponse:
    """The template streamed as ``text/html``, each part as it is known.
    Values are not HTML-escaped (as in Effect)."""
    chunks = _template.stream(strings, *args).encode_text()
    return stream(cast("Stream[bytes, object]", chunks), content_type="text/html")

json

json(body, **options) -> Effect[HttpServerResponse, _body.HttpBodyError]

body as JSON, failing when it has no JSON form.

ParameterTypeDescription
bodyobject
optionsUnpack[ContentTypeOptions] = {}

Returns Effect[HttpServerResponse, _body.HttpBodyError]

def json(
    body: object, **options: Unpack[ContentTypeOptions]
) -> Effect[HttpServerResponse, _body.HttpBodyError]:
    """``body`` as JSON, failing when it has no JSON form."""
    headers = _headers(options)
    return _body.json(body, _content_type(options, headers)).map(
        lambda encoded: _make(options, 200, headers, encoded)
    )

json_unsafe

json_unsafe(body, **options) -> HttpServerResponse

body as JSON; raises when it has no JSON form.

ParameterTypeDescription
bodyobject
optionsUnpack[ContentTypeOptions] = {}

Returns HttpServerResponse

def json_unsafe(body: object, **options: Unpack[ContentTypeOptions]) -> HttpServerResponse:
    """``body`` as JSON; raises when it has no JSON form."""
    headers = _headers(options)
    return _make(options, 200, headers, _body.json_unsafe(body, _content_type(options, headers)))

file

file(path, **options) -> Effect[HttpServerResponse, PlatformError, HttpPlatform]

The file at path, streamed by the HttpPlatform.

ParameterTypeDescription
pathstr
optionsUnpack[FileOptions] = {}

Returns Effect[HttpServerResponse, PlatformError, HttpPlatform]

def file(
    path: str, **options: Unpack[FileOptions]
) -> Effect[HttpServerResponse, PlatformError, HttpPlatform]:
    """The file at ``path``, streamed by the ``HttpPlatform``."""
    from pyfect.http.platform import HttpPlatform

    return HttpPlatform().flat_map(lambda platform: platform.file_response(path, **options))

file_web

file_web(file, **options) -> Effect[HttpServerResponse, Never, HttpPlatform]

A file-like value, streamed by the HttpPlatform.

ParameterTypeDescription
fileFileLike
optionsUnpack[FileWebOptions] = {}

Returns Effect[HttpServerResponse, Never, HttpPlatform]

def file_web(
    file: FileLike, **options: Unpack[FileWebOptions]
) -> Effect[HttpServerResponse, Never, HttpPlatform]:
    """A file-like value, streamed by the ``HttpPlatform``."""
    from pyfect.http.platform import HttpPlatform

    return HttpPlatform().flat_map(lambda platform: platform.file_web_response(file, **options))

schema_json

schema_json[T, RE](schema, **options) -> JsonResponder[T, RE]

JSON responses of schema's values, encoded by the schema.

ParameterTypeDescription
schemaCodec[T, object, object, RE]
optionsUnpack[ParseOptions] = {}

Returns JsonResponder[T, RE]

def schema_json[T, RE](
    schema: Codec[T, object, object, RE], **options: Unpack[ParseOptions]
) -> JsonResponder[T, RE]:
    """JSON responses of ``schema``'s values, encoded by the schema."""
    return JsonResponder(schema, options)

url_params

url_params(body, **options) -> HttpServerResponse

The parameters form-encoded, application/x-www-form-urlencoded by default.

ParameterTypeDescription
body_url_params.Input
optionsUnpack[ContentTypeOptions] = {}

Returns HttpServerResponse

def url_params(
    body: _url_params.Input, **options: Unpack[ContentTypeOptions]
) -> HttpServerResponse:
    """The parameters form-encoded, ``application/x-www-form-urlencoded``
    by default."""
    headers = _headers(options)
    content_type = _content_type(options, headers) or "application/x-www-form-urlencoded"
    return _make(options, 200, headers, _body.text(_url_params.to_string(body), content_type))

raw

raw(body, **options) -> HttpServerResponse

A body the server writes as it is (bytes, str).

ParameterTypeDescription
bodyobject
optionsUnpack[RawOptions] = {}

Returns HttpServerResponse

def raw(body: object, **options: Unpack[RawOptions]) -> HttpServerResponse:
    """A body the server writes as it is (bytes, ``str``)."""
    return HttpServerResponse(
        options.get("status", 200),
        options.get("status_text"),
        None if options.get("headers") is None else _headers(options),
        options.get("cookies"),
        _body.raw(
            body,
            content_type=options.get("content_type"),
            content_length=options.get("content_length"),
        ),
    )

form_data

form_data(body, **options) -> HttpServerResponse

A multipart form; the server writes its content type.

ParameterTypeDescription
body_body.FormData
optionsUnpack[Options] = {}

Returns HttpServerResponse

def form_data(body: _body.FormData, **options: Unpack[Options]) -> HttpServerResponse:
    """A multipart form; the server writes its content type."""
    return HttpServerResponse(
        options.get("status", 200),
        options.get("status_text"),
        None if options.get("headers") is None else _headers(options),
        options.get("cookies"),
        body,
    )

stream

stream(body, **options) -> HttpServerResponse

A body written as it is pulled.

ParameterTypeDescription
bodyStream[bytes, object]
optionsUnpack[RawOptions] = {}

Returns HttpServerResponse

def stream(body: Stream[bytes, object], **options: Unpack[RawOptions]) -> HttpServerResponse:
    """A body written as it is pulled."""
    headers = _headers(options)
    return _make(
        options,
        200,
        headers,
        _body.stream(body, _content_type(options, headers), options.get("content_length")),
    )

omits_body

omits_body(response, without_body=False) -> bool

Whether the response is sent without its body (without_body, as for HEAD, or a 204, 205 or 304 status).

ParameterTypeDescription
responseHttpServerResponse
without_bodybool = False

Returns bool

def omits_body(response: HttpServerResponse, without_body: bool = False) -> bool:
    """Whether the response is sent without its body (``without_body``, as
    for ``HEAD``, or a 204, 205 or 304 status)."""
    return without_body or response.status in (204, 205, 304)

omits_content_length

omits_content_length(status) -> bool

204 and 205 responses drop content-length; HEAD and 304 keep the representation's.

ParameterTypeDescription
statusint

Returns bool

def omits_content_length(status: int) -> bool:
    """204 and 205 responses drop ``content-length``; HEAD and 304 keep the
    representation's."""
    return status in (204, 205)

to_client_response

to_client_response(response, *, request=None) -> HttpClientResponse

response as an HttpClientResponse to request (by default an empty one, whose response URL is "").

ParameterTypeDescription
responseHttpServerResponse
requestHttpClientRequest | None = None

Returns HttpClientResponse

def to_client_response(
    response: HttpServerResponse, *, request: HttpClientRequest | None = None
) -> HttpClientResponse:
    """``response`` as an ``HttpClientResponse`` to ``request`` (by default
    an empty one, whose response URL is ``""``)."""
    return _ServerClientResponse(_EMPTY_REQUEST if request is None else request, response)

parse_content_length

parse_content_length(value) -> int | None

A content-length value of digits only, as an exact JavaScript number; anything else is unknown.

ParameterTypeDescription
valuestr | None

Returns int | None

def parse_content_length(value: str | None) -> int | None:
    """A ``content-length`` value of digits only, as an exact JavaScript
    number; anything else is unknown."""
    parsed = None if value is None else parse_digits(value)
    return parsed if parsed is not None and parsed <= 2**53 - 1 else None

from_client_response

from_client_response(response) -> HttpServerResponse

A server response streaming response's body, with its status, headers and cookies (no body becomes an empty stream).

ParameterTypeDescription
responseHttpClientResponse

Returns HttpServerResponse

def from_client_response(response: HttpClientResponse) -> HttpServerResponse:
    """A server response streaming ``response``'s body, with its status,
    headers and cookies (no body becomes an empty stream)."""
    headers = response.headers.remove("set-cookie")
    chunks = response.stream.catch_if(_is_empty_body_error, lambda _: empty_stream)
    return HttpServerResponse(
        response.status,
        headers=headers,
        cookies=response.cookies,
        body=_body.stream(
            cast("Stream[bytes, object]", chunks),
            headers.get("content-type"),
            parse_content_length(headers.get("content-length")),
        ),
    )

die_with

die_with(response) -> Effect[Never]

Die with response as the defect; servers send it as is (Effect's Effect.die(response)).

ParameterTypeDescription
responseHttpServerResponse

Returns Effect[Never]

def die_with(response: HttpServerResponse) -> Effect[Never]:
    """Die with ``response`` as the defect; servers send it as is (Effect's
    ``Effect.die(response)``)."""
    return die(response)

response_of_defect

response_of_defect(defect) -> HttpServerResponse | None

The response a defect carries.

ParameterTypeDescription
defectobject

Returns HttpServerResponse | None

def response_of_defect(defect: object) -> HttpServerResponse | None:
    """The response a defect carries."""
    return defect if isinstance(defect, HttpServerResponse) else None