or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

app.mdexpress.mdindex.mdreactive.mdrender.mdsession.mdtypes.mdui.md

app.mddocs/

0

# Application Framework

1

2

Core application class, lifecycle management, and deployment utilities for creating and running Shiny applications. The App class is the foundation of every Shiny application, combining UI definitions with server logic.

3

4

```python

5

# Required imports for this module

6

from shiny import App, run_app, req

7

from shiny import Inputs, Outputs, Session

8

from typing import Callable, Literal, Mapping

9

from htmltools import Tag, TagList

10

from starlette.requests import Request

11

from pathlib import Path

12

```

13

14

## Capabilities

15

16

### App Class

17

18

The main application class that combines UI and server components into a deployable web application.

19

20

```python { .api }

21

class App:

22

"""

23

Create a Shiny application.

24

25

Args:

26

ui: The user interface definition. Can be a Tag, TagList, function that

27

returns UI, or a file path to UI definition.

28

server: Server function that defines reactive logic. Can take just Inputs

29

or Inputs, Outputs, and Session parameters.

30

static_assets: Path to directory containing static files, or mapping of

31

URL paths to file paths.

32

bookmark_store: Bookmark storage strategy ("url", "server", or "disable").

33

debug: Enable debug mode for development.

34

"""

35

def __init__(

36

self,

37

ui: Tag | TagList | Callable[[Request], Tag | TagList] | Path,

38

server: Callable[[Inputs], None] | Callable[[Inputs, Outputs, Session], None] | None = None,

39

*,

40

static_assets: str | Path | Mapping[str, str | Path] | None = None,

41

bookmark_store: Literal["url", "server", "disable"] = "disable",

42

debug: bool = False,

43

): ...

44

45

# Application configuration

46

lib_prefix: str = "lib/"

47

sanitize_errors: bool = False

48

```

49

50

#### Usage Examples

51

52

```python

53

from shiny import App, ui, render, Inputs, Outputs, Session

54

55

# Basic application

56

app_ui = ui.page_fluid(

57

ui.h1("My Application"),

58

ui.input_text("name", "Enter your name:"),

59

ui.output_text("greeting")

60

)

61

62

def server(input: Inputs, output: Outputs, session: Session):

63

@output

64

@render.text

65

def greeting():

66

return f"Hello, {input.name()}!"

67

68

app = App(app_ui, server)

69

70

# Application with static assets

71

app = App(

72

app_ui,

73

server,

74

static_assets="www", # Serve files from 'www' directory

75

debug=True # Enable debug mode

76

)

77

78

# Dynamic UI function

79

def dynamic_ui():

80

return ui.page_fluid(

81

ui.h1(f"Generated at {datetime.now()}"),

82

ui.p("This UI is generated dynamically")

83

)

84

85

app = App(dynamic_ui, server)

86

```

87

88

### Application Running

89

90

Functions for running and deploying Shiny applications in various environments.

91

92

```python { .api }

93

def run_app(

94

app: str | App = "app:app",

95

host: str = "127.0.0.1",

96

port: int = 8000,

97

*,

98

autoreload_port: int = 0,

99

reload: bool = False,

100

reload_dirs: list[str] | None = None,

101

reload_includes: list[str] | tuple[str, ...] = ("*.py", "*.css", "*.js", "*.html", "*.yml"),

102

reload_excludes: list[str] | tuple[str, ...] = (".*", "*.pyc"),

103

ws_max_size: int = 16777216,

104

log_level: str | None = None,

105

app_dir: str | None = ".",

106

factory: bool = False,

107

launch_browser: bool = False,

108

dev_mode: bool = True,

109

**kwargs: object,

110

) -> None:

111

"""

112

Run a Shiny application.

113

114

Args:

115

app: App instance or app module string (default "app:app").

116

host: Hostname to bind to.

117

port: Port number (default 8000).

118

autoreload_port: Port for auto-reload server.

119

reload: Enable file watching and auto-reload.

120

reload_dirs: Directories to watch for changes.

121

reload_includes: File patterns to include in watching.

122

reload_excludes: File patterns to exclude from watching.

123

ws_max_size: Maximum WebSocket message size.

124

log_level: Logging level for the server.

125

app_dir: Directory containing the app.

126

factory: Treat app as a factory function.

127

launch_browser: Automatically open browser.

128

dev_mode: Enable development mode features.

129

**kwargs: Additional arguments passed to the ASGI server.

130

"""

131

```

132

133

#### Usage Examples

134

135

```python

136

# Run app instance directly

137

app = App(ui_def, server_func)

138

shiny.run_app(app)

139

140

# Run with custom host and port

141

shiny.run_app(app, host="0.0.0.0", port=8080)

142

143

# Run with auto-reload for development

144

shiny.run_app(app, reload=True, dev_mode=True)

145

146

# Run from module string (default behavior)

147

shiny.run_app("my_app:app")

148

149

# Run with custom file watching patterns

150

shiny.run_app(app, reload=True, reload_includes=["*.py", "*.css"], reload_excludes=["**/temp/*"])

151

152

# Run from directory (looks for app.py)

153

shiny.run_app("./my_shiny_project/")

154

```

155

156

### Application Validation

157

158

Utilities for validating application state and handling requirements.

159

160

```python { .api }

161

def req(

162

*args: object,

163

cancel_output: bool | Literal["progress"] = False

164

) -> None:

165

"""

166

Require that values are truthy, throwing a silent exception if not.

167

168

Args:

169

*args: Values to check for truthiness.

170

cancel_output: If True, cancel current output. If "progress",

171

cancel only progress indicators.

172

173

Raises:

174

SilentException: If any argument is falsy.

175

"""

176

```

177

178

#### Usage Examples

179

180

```python

181

def server(input: Inputs, output: Outputs, session: Session):

182

@output

183

@render.text

184

def analysis():

185

# Require that inputs are provided before proceeding

186

req(input.dataset(), input.variable())

187

188

# This code only runs if both inputs have truthy values

189

return perform_analysis(input.dataset(), input.variable())

190

191

@output

192

@render.plot

193

def plot():

194

# Multiple requirements

195

req(

196

input.x_var(),

197

input.y_var(),

198

input.data_file() is not None

199

)

200

201

# Cancel output without clearing existing output

202

req(len(input.selected_rows()) > 0, cancel_output=True)

203

204

return create_plot(input.x_var(), input.y_var(), input.selected_rows())

205

```

206

207

### Application Context

208

209

Utilities for working with application context and environment detection.

210

211

```python { .api }

212

def get_current_session() -> Session | None:

213

"""

214

Get the current session if running within a Shiny application context.

215

216

Returns:

217

Current session or None if not in application context.

218

"""

219

220

def require_active_session(what: str | None = None) -> Session:

221

"""

222

Require that there is an active session context.

223

224

Args:

225

what: Description of what requires an active session.

226

227

Returns:

228

Current session.

229

230

Raises:

231

RuntimeError: If no active session.

232

"""

233

```

234

235

#### Usage Examples

236

237

```python

238

from shiny.session import get_current_session, require_active_session

239

240

# Check for session context

241

session = get_current_session()

242

if session:

243

session.send_custom_message("alert", {"message": "Hello!"})

244

245

# Require session context

246

def some_utility_function():

247

session = require_active_session("send custom message")

248

session.send_custom_message("notification", {"text": "Processing..."})

249

```

250

251

### Environment Detection

252

253

Automatic detection and handling of different deployment environments.

254

255

```python { .api }

256

# Environment detection (internal)

257

_is_pyodide: bool # True if running in Pyodide/browser environment

258

_in_pytest: bool # True if running in pytest

259

```

260

261

**Note**: Some features like `run_app()` are automatically disabled in Pyodide environments where they are not supported.

262

263

## Application Deployment Patterns

264

265

### Development Deployment

266

267

```python

268

# app.py - Development server

269

from shiny import App, ui, render, Inputs, Outputs, Session

270

271

app_ui = ui.page_fluid(

272

# UI definition

273

)

274

275

def server(input: Inputs, output: Outputs, session: Session):

276

# Server logic

277

pass

278

279

app = App(app_ui, server, debug=True)

280

281

if __name__ == "__main__":

282

shiny.run_app(app, autoreload=True)

283

```

284

285

### Production Deployment

286

287

```python

288

# app.py - Production configuration

289

from shiny import App, ui, render

290

291

app_ui = ui.page_fluid(

292

# UI definition

293

)

294

295

def server(input, output, session):

296

# Server logic

297

pass

298

299

# Production app without debug mode

300

app = App(app_ui, server, sanitize_errors=True)

301

302

# For ASGI servers like Uvicorn, Gunicorn

303

# uvicorn app:app --host 0.0.0.0 --port 8000

304

```

305

306

### Static Asset Handling

307

308

```python

309

# Serve static files from 'www' directory

310

app = App(

311

ui_definition,

312

server_function,

313

static_assets="www" # Files in www/ served at /static/

314

)

315

316

# Reference static files in UI

317

app_ui = ui.page_fluid(

318

ui.img(src="static/logo.png"), # References www/logo.png

319

ui.include_css("static/custom.css") # References www/custom.css

320

)

321

```