Skip to content

Commit 9fa7922

Browse files
committed
Add session_on_end example
1 parent 00cb74f commit 9fa7922

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
from starlette.requests import Request
2+
3+
from shiny import App, Inputs, Outputs, Session, reactive, render, ui
4+
from shiny.bookmark import BookmarkState
5+
6+
7+
# App UI **must** be a function to ensure that each user restores their own UI values.
8+
def app_ui(request: Request):
9+
return ui.page_fluid(
10+
ui.markdown(
11+
"Directions: "
12+
"\n1. Change the radio buttons below"
13+
"\n2. Changing the radio button will cause a server error."
14+
"\n3. The app will save the state to the URL before disconnecting."
15+
"\n4. Refresh, your browser. The radio button selection should persist."
16+
),
17+
ui.hr(),
18+
ui.input_radio_buttons(
19+
"letter",
20+
"Pick a letter",
21+
choices=["A", "B", "C"],
22+
),
23+
"Selection:",
24+
ui.output_code("letter_out"),
25+
)
26+
27+
28+
def server(input: Inputs, output: Outputs, session: Session):
29+
30+
@render.code
31+
def letter_out():
32+
return input.letter()
33+
34+
@reactive.effect
35+
@reactive.event(input.letter, ignore_init=True)
36+
async def _():
37+
# Simulate a server error when the radio button is changed
38+
raise RuntimeError("Simulated server error")
39+
40+
# When the session ends, update the query string with the latest bookmark information
41+
@session.on_end
42+
async def _():
43+
await session.bookmark.update_query_string()
44+
45+
# Reset query string when restoring state
46+
@session.bookmark.on_restored
47+
async def _(state: BookmarkState):
48+
await session.bookmark.update_query_string(session.clientdata.url_pathname())
49+
50+
51+
# Make sure to set the bookmark_store to `"url"` (or `"server"`)
52+
# to store the bookmark information/key in the URL query string.
53+
app = App(app_ui, server, bookmark_store="url")

shiny/session/_session.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,7 @@ async def close(self, code: int = 1001) -> None:
211211
@abstractmethod
212212
def _is_hidden(self, name: str) -> bool: ...
213213

214+
@add_example("session_on_end")
214215
@abstractmethod
215216
def on_end(
216217
self,

0 commit comments

Comments
 (0)