shiny.Session.dynamic_route#

Session.dynamic_route(name, handler)#

Register a function to call when a dynamically generated, session-specific, route is requested.

Provides a convenient way to serve-up session-dependent values for other clients/applications to consume.

Parameters
  • name (str) – A name for the route (used to determine part of the URL path).

  • handler (Callable[[Request], Callable[[MutableMapping[str, Any], Callable[[], Awaitable[MutableMapping[str, Any]]], Callable[[MutableMapping[str, Any]], Awaitable[None]]], Awaitable[None]]]) – The function to call when a request is made to the route. This function should take a single argument (a starlette.requests.Request object) and return a starlette.types.ASGIApp object.

Return type

The URL path for the route.

Example

#| standalone: true
#| layout: vertical
from shiny import *
from starlette.responses import JSONResponse
from starlette.requests import Request

app_ui = ui.page_fluid(
    ui.input_action_button("serve", "Click to serve"), ui.div(id="messages")
)

def server(input: Inputs, output: Outputs, session: Session):
    @reactive.Effect
    @reactive.event(input.serve)
    def _():
        async def my_handler(request: Request) -> JSONResponse:
            return JSONResponse({"n_clicks": input.serve()}, status_code=200)

        path = session.dynamic_route("my_handler", my_handler)

        print("Serving at: ", path)

        ui.insert_ui(
            ui.tags.script(
                f"""
                fetch('{path}')
                  .then(r => r.json())
                  .then(x => {{ $('#messages').text(`Clicked ${{x.n_clicks}} times`); }});
                """
            ),
            selector="body",
        )


app = App(app_ui, server)