Client Actions
When a user changes data on the server, the page may need fresh data to reflect that change. Actions connect that server operation to the client update.
Define an action in your Python controller and call it from the client through a generated JavaScript function. Its request and response types come from the Python signature.
Action Types
Actions use POST requests, which you can inspect in your browser's network tools. Choose the decorator based on what the client needs after the request:
@sideeffect: Run the action, call render() again, and update the client's render data. Use this when a mutation changes data displayed on the page. A sideeffect can also return a separate response payload.
@passthrough: Run the action and return its response without refreshing render data. Use this to fetch additional data or perform a mutation that doesn't affect the current view.
Side Effect
After a sideeffect finishes, Mountaineer calls render() and merges the result into the client's server state. The browser stays on the page, preserving local React state such as an open menu or an unfinished input.
@sideeffect can either be called with default behavior or customized via decorator arguments:
# no parameters, refresh all state
@sideeffect
def increment_count(self) -> None:
self.global_count += 1
@sideeffect(
# only push the updated current_count variable to the client
reload=(CountRender.current_count,)
)
def increment_count(self) -> None:
self.global_count += 1
# execute a sideeffect and then return additional data from a custom data model
@sideeffect
def increment_count(self) -> CustomDataModel:
self.global_count += 1
...
return CustomDataModel(...)
Call the sideeffect from the client through serverState:
const response = await serverState.increment_count({
requestBody: {
count: 5,
},
});
You can also manually inspect the sideeffect payload by accessing response.sideeffect.
If the action has a passthrough, it will be supplied in response.passthrough. Otherwise it will be undefined.
Experimental Render Reloader
!!! warning
This feature is experimental and only supports relatively simple render() function implementations. If you use it for a more complicated render() function and it doesn't work as expected, report a bug to improve the test coverage.
A render function may query several tables or perform expensive calculations. A sideeffect that changes only one field can end up repeating all that work.
The reload filter limits which fields are sent to the frontend, but still runs the full render function. To also skip calculations for other fields, set experimental_render_reload=True.
Mountaineer inspects the function's AST (Abstract Syntax Tree) and compiles a reduced render function for the requested fields. In this example, reloading only value_a can skip the larger prime calculation:
def render(
self,
query_id: int,
) -> ExampleRenderModel:
a = calculate_primes(10000)
b = calculate_primes(1000000)
return ExampleRenderModel(
value_a=f"Hello {a}",
value_b=f"World {b}",
)
@sideeffect(
reload=(ExampleRenderModel.value_a,),
experimental_render_reload=use_experimental,
)
def call_sideeffect(self, payload: dict) -> None:
pass
Benchmarked on a Macbook M1, calling this initial render will perform ~1.84s of compute. It results in:
{
"value_a": "Hello 1229",
"value_b": "Hello 78498"
}
When call_sideeffect is called with experimental_render_reload=True, the compute only takes 0.010s. It results in:
{
"value_a": "Hello 1229"
}
Passthrough
@passthrough returns the action's result without calling render(). It can return no value or a response model:
# no parameters, no response model
@passthrough
def server_action(self) -> None:
pass
# execute a passthrough and then return additional data from a custom data model
@passthrough
def server_action(self) -> CustomDataModel:
pass
Like passthrough values in sideeffects, you can access it on the client side like:
const response = await serverState.server_action({});
console.log(response.passthrough);
Streaming Responses
To send updates as work progresses, return an async generator from a passthrough action. Annotate its return type with typing.AsyncIterator:
from typing import AsyncIterator
from mountaineer import passthrough, ControllerBase
from pydantic import BaseModel
class MyMetadata(BaseModel):
state: int
class MyController(ControllerBase):
...
@passthrough
async def stream_metadata(self) -> AsyncIterator[MyMetadata]:
yield MyMetadata(state=1)
await asyncio.sleep(10)
yield MyMetadata(state=2)
Streaming is supported only by @passthrough. Each yield sends a value to the client without refreshing render data.
Consume the stream with for await. The generated client types describe each response:
import React, { useState, useEffect } from "react";
const Page = () => {
const [currentState, setCurrentState] = useState(-1);
useEffect(() => {
const runStream = async () => {
const responseStream = await serverState.stream_metadata({});
for await (const response of responseStream) {
setCurrentState(response.passthrough.state);
}
};
runStream();
}, []);
return <div>{currentState}</div>;
}
You'll see the first event state 1 for 10 seconds, then it will update to 2.
Action Definitions
Action signatures support:
- Query parameters
- Pydantic models for JSON payloads
- Dependency injection via
fastapi.Depends
Actions can be synchronous or asynchronous. Synchronous actions run in a thread pool. Prefer async actions when the libraries they call support await, so waiting for I/O doesn't occupy a thread.
A common sideeffect pattern might look like this:
from mountaineer import ControllerBase, Depends
from my_website.models import User
from my_website.deps import get_current_user
class IncrementCountRequest:
count: int
class MyController(ControllerBase):
def __init__(self):
super().__init__()
self.global_count = 0
@sideeffect
async def increment_count(
self,
payload: IncrementCountRequest,
query_param: int,
user: User = Depends(get_current_user)
) -> None:
self.global_count += payload.count
!!! warning
Actions are publicly exposed to the Internet by default. It's up to you to secure them with authentication if they should only be accessible by a certain portion of your userbase.