GitHub

API reference for asgi.

ASGI: HTTP apps on any ASGI 3 server, and ASGI applications inside apps.

to_asgi(app, layer) is an ASGI application for uvicorn, hypercorn, granian or a host framework (FastAPI's app.mount). Its lifespan scope builds the layer in a ManagedRuntime and releases it at shutdown; each request runs on its own fiber on the server's loop::

app = router.to_http_effect(routes)
asgi_app = asgi.to_asgi(app, services)  # uvicorn module:asgi_app

Request bodies are streams that wait for the client; streamed responses are sent chunk by chunk; a client disconnect interrupts the request (a client abort, 499) and stops its body. A websocket scope is a GET request whose upgrade is a WebSocket Socket (request.upgrade accepts it); an app that does not upgrade answers with its response. Under a host framework's Mount, root_path is removed from the request's URL. Host frameworks send no lifespan to mounted apps: pass asgi_app.lifespan() to the host's own (FastAPI(lifespan=lambda _: asgi_app.lifespan())).

router.to_asgi(routes) serves a router's routes the same way.

The other way round, from_asgi(fastapi_app) is an app answering with another framework's application, mountable under a router prefix (root_path is the prefix), and lifespan(fastapi_app) runs its startup and shutdown in a scope. pyfect.http.uvicorn_server serves an app on a port with uvicorn (extra pyfect-dev[server]).

Values

AttributeTypeDescription
HIGH_WATER_MARKLiteral[65536]

Types

TypeDefinitionDescription
AsgiApplicationtype AsgiApplication = Callable[[Scope, Receive, Send], Awaitable[None]]
Messagetype Message = MutableMapping[str, Any]
Receivetype Receive = Callable[[], Awaitable[Message]]
Scopetype Scope = MutableMapping[str, Any]
Sendtype Send = Callable[[Message], Awaitable[None]]

Classes

Functions

to_asgi

to_asgi[E](app: Effect[HttpServerResponse, E, _Served], /, *, middleware: HttpMiddleware | None = None) -> AsgiApp
to_asgi[E, R, LE](app: Effect[HttpServerResponse, E, R | _Served], layer: Layer[R, LE], /, *, middleware: HttpMiddleware | None = None, memo_map: MemoMap | None = None) -> AsgiApp

app (through middleware) as an ASGI 3 application for uvicorn, hypercorn, granian or a host framework, with the services of layer. HEAD responses have no body; request bodies are streams; streamed responses are sent as they are produced; a client disconnect interrupts the request; WebSocket requests are upgraded through request.upgrade.

ParameterTypeDescription
app
layer= None
middleware= None
memo_map= None
@overload
def to_asgi[E](
    app: Effect[HttpServerResponse, E, _Served],
    /,
    *,
    middleware: HttpMiddleware | None = None,
) -> AsgiApp: ...
@overload
def to_asgi[E, R, LE](
    app: Effect[HttpServerResponse, E, R | _Served],
    layer: Layer[R, LE],
    /,
    *,
    middleware: HttpMiddleware | None = None,
    memo_map: MemoMap | None = None,
) -> AsgiApp: ...
def to_asgi(
    app: Effect[HttpServerResponse, Any, Any],
    layer: Layer[Any, Any] | None = None,
    /,
    *,
    middleware: HttpMiddleware | None = None,
    memo_map: MemoMap | None = None,
) -> AsgiApp:
    """``app`` (through ``middleware``) as an ASGI 3 application for
    uvicorn, hypercorn, granian or a host framework, with the services of
    ``layer``. ``HEAD`` responses have no body; request bodies are
    streams; streamed responses are sent as they are produced; a client
    disconnect interrupts the request; WebSocket requests are upgraded
    through ``request.upgrade``."""
    require_effect(app, "app")
    if layer is not None:
        require_layer(layer, "layer")
    runtime = ManagedRuntime.make(empty_layer if layer is None else layer, memo_map=memo_map)
    return AsgiApp(app, runtime, middleware)

to_asgi_with

to_asgi_with[LE](layer, to_app, *, middleware=None, memo_map=None) -> AsgiApp

to_asgi for the app to_app makes of layer's services once they are built (what router.to_asgi serves routes with).

ParameterTypeDescription
layerLayer[Any, LE]
to_appCallable[[Context[Any]], Effect[HttpServerResponse, Any, Any]]
middlewareHttpMiddleware | None = None
memo_mapMemoMap | None = None

Returns AsgiApp

def to_asgi_with[LE](
    layer: Layer[Any, LE],
    to_app: Callable[[Context[Any]], Effect[HttpServerResponse, Any, Any]],
    *,
    middleware: HttpMiddleware | None = None,
    memo_map: MemoMap | None = None,
) -> AsgiApp:
    """``to_asgi`` for the app ``to_app`` makes of ``layer``'s services once
    they are built (what ``router.to_asgi`` serves routes with)."""
    require_layer(layer, "layer")

    def make(fiber: Fiber[Any, Any]) -> Effect[Effect[HttpServerResponse, Any, Any]]:
        return succeed(to_app(fiber._context))

    served = layer_effect(_ServedApp, _WithFiber(make)).pipe(provide_merge(layer))
    runtime = ManagedRuntime.make(served, memo_map=memo_map)
    app: Effect[HttpServerResponse, Any, Any] = _WithFiber(_served)
    return AsgiApp(app, runtime, middleware)

from_asgi

from_asgi(app, *, state=None) -> Effect[HttpServerResponse, HttpServerError, HttpServerRequest]

An app answering with the ASGI application app (Effect's fromWebHandler for ASGI). HTTP only, as fromWebHandler: a WebSocket upgrade reaches app as an http scope. Mounted under a router prefix (router.prefix_route), the prefix is the scope's root_path; on a plain "/admin/*" route root_path is empty and path is the whole path. state is the scope's state (what lifespan gives). Interrupting the app cancels the call.

ParameterTypeDescription
appAsgiApplication
stateMapping[str, Any] | None = None

Returns Effect[HttpServerResponse, HttpServerError, HttpServerRequest]

def from_asgi(
    app: AsgiApplication, *, state: Mapping[str, Any] | None = None
) -> Effect[HttpServerResponse, HttpServerError, HttpServerRequest]:
    """An app answering with the ASGI application ``app`` (Effect's
    ``fromWebHandler`` for ASGI). HTTP only, as ``fromWebHandler``: a
    WebSocket upgrade reaches ``app`` as an ``http`` scope. Mounted under a
    router prefix (``router.prefix_route``), the prefix is the scope's
    ``root_path``; on a plain ``"/admin/*"`` route ``root_path`` is empty and
    ``path`` is the whole path. ``state`` is the scope's ``state`` (what
    ``lifespan`` gives). Interrupting the app cancels the call."""

    def run(fiber: Fiber[Any, Any]) -> Effect[HttpServerResponse, HttpServerError]:
        request = fiber._context.get_unsafe(HttpServerRequest)
        controller = AbortController()
        match request_to_web(request, signal=controller.signal, context=fiber._context):
            case Err(reason):
                return fail(HttpServerError(reason))
            case Ok(web):
                pass
        scope = _scope(request, state)
        body = None if web.body is None else web.chunks()
        exchanges: list[_Exchange] = []

        async def call() -> WebResponse:
            exchange = _Exchange(app, scope, body)
            exchanges.append(exchange)
            try:
                return await _call(exchange)
            except asyncio.CancelledError:
                controller.abort()
                raise

        def on_error(cause: Exception) -> HttpServerError:
            return HttpServerError(InternalError(request, "HttpApp.fromAsgi: Error in app", cause))

        called = try_async(call, on_error).map(response_from_web)
        found, request_scope = fiber._context.lookup(Scope)
        if not found:
            return called

        # The request's scope closes once the response ended, however it
        # ended: its body read or dropped, never sent (HEAD, 204, 304), or
        # the client gone.
        def finish(_exit: Exit[Any, Any]) -> Effect[None]:
            return sync(lambda: [exchange.finish() for exchange in exchanges]).as_void()

        return request_scope.add_finalizer(finish).and_then(called)

    return _WithFiber(run)

lifespan

lifespan(app) -> Effect[dict[str, Any], AsgiLifespanError, Scope]

Start app's lifespan (its startup handlers) and shut it down when the scope closes; succeeds with the lifespan state to pass to from_asgi. An application without lifespan support starts at once.

ParameterTypeDescription
appAsgiApplication

Returns Effect[dict[str, Any], AsgiLifespanError, Scope]

def lifespan(app: AsgiApplication) -> Effect[dict[str, Any], AsgiLifespanError, Scope]:
    """Start ``app``'s lifespan (its startup handlers) and shut it down when
    the scope closes; succeeds with the lifespan ``state`` to pass to
    ``from_asgi``. An application without lifespan support starts at once."""

    async def start() -> _Lifespan:
        running = _Lifespan(app)
        await running.startup()
        return running

    def on_error(cause: Exception) -> AsgiLifespanError:
        return cause if isinstance(cause, AsgiLifespanError) else AsgiLifespanError(str(cause))

    return acquire_release(
        try_async(start, on_error), lambda running, _exit: from_async(running.shutdown)
    ).map(lambda running: running.state)