pypi-streamlit

Description
The fastest way to build and share data apps
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/pypi-streamlit@1.16.0

caching-config.md docs/

1
# Configuration, Caching, and State Management
2
3
Application configuration, performance optimization through caching decorators, session state management, and utility functions for app lifecycle control. These capabilities help you build performant, stateful applications with proper configuration management.
4
5
## Capabilities
6
7
### Page Configuration
8
9
Configure global app settings and appearance.
10
11
```python { .api }
12
def set_page_config(
13
page_title: str = None,
14
page_icon: str = None,
15
layout: str = "centered",
16
initial_sidebar_state: str = "auto",
17
menu_items: dict = None
18
) -> None:
19
"""
20
Configure the page settings (must be first Streamlit command).
21
22
Parameters:
23
- page_title: Title shown in browser tab
24
- page_icon: Icon shown in browser tab (emoji or image URL)
25
- layout: Page layout ("centered" or "wide")
26
- initial_sidebar_state: Initial sidebar state ("auto", "expanded", "collapsed")
27
- menu_items: Custom menu items dictionary
28
"""
29
```
30
31
#### Usage Example
32
33
```python
34
import streamlit as st
35
36
# Configure page (must be first Streamlit command)
37
st.set_page_config(
38
page_title="My Data App",
39
page_icon="๐Ÿ“Š",
40
layout="wide",
41
initial_sidebar_state="expanded",
42
menu_items={
43
'Get Help': 'https://docs.streamlit.io/',
44
'Report a bug': "https://github.com/myorg/myapp/issues",
45
'About': "This is a demo app built with Streamlit!"
46
}
47
)
48
49
st.title("Welcome to My App")
50
```
51
52
### Configuration Options
53
54
Access and modify Streamlit's configuration system.
55
56
```python { .api }
57
def get_option(key: str):
58
"""
59
Get the value of a configuration option.
60
61
Parameters:
62
- key: Configuration key (e.g., "theme.primaryColor")
63
64
Returns:
65
The current value of the configuration option
66
"""
67
68
def set_option(key: str, value) -> None:
69
"""
70
Set the value of a configuration option.
71
72
Parameters:
73
- key: Configuration key (e.g., "theme.primaryColor")
74
- value: New value for the configuration option
75
"""
76
```
77
78
#### Usage Example
79
80
```python
81
import streamlit as st
82
83
# Get current configuration
84
current_theme = st.get_option("theme.base")
85
st.write(f"Current theme: {current_theme}")
86
87
# Set configuration options
88
st.set_option("theme.primaryColor", "#FF6B6B")
89
st.set_option("theme.backgroundColor", "#FFFFFF")
90
91
# Common configuration options
92
st.write("Available config categories:")
93
st.write("- theme.*: UI theme settings")
94
st.write("- server.*: Server configuration")
95
st.write("- browser.*: Browser behavior")
96
st.write("- logger.*: Logging configuration")
97
```
98
99
### Legacy Caching
100
101
Traditional caching decorator for expensive computations.
102
103
```python { .api }
104
@cache(persist: bool = False, allow_output_mutation: bool = False, suppress_st_warning: bool = False, hash_funcs: dict = None, max_entries: int = None, ttl: float = None, show_spinner: bool = True)
105
def cached_function():
106
"""
107
Decorator for caching function results (legacy).
108
109
Parameters:
110
- persist: Whether to persist cache across sessions
111
- allow_output_mutation: Whether to allow mutation of cached results
112
- suppress_st_warning: Whether to suppress Streamlit warnings
113
- hash_funcs: Custom hash functions for parameters
114
- max_entries: Maximum number of cache entries
115
- ttl: Time-to-live in seconds
116
- show_spinner: Whether to show spinner during computation
117
"""
118
```
119
120
#### Usage Example
121
122
```python
123
import streamlit as st
124
import pandas as pd
125
import time
126
127
@st.cache
128
def load_data(file_path):
129
"""Load data with caching to avoid repeated file reads."""
130
time.sleep(2) # Simulate expensive operation
131
return pd.read_csv(file_path)
132
133
@st.cache(ttl=3600) # Cache for 1 hour
134
def fetch_api_data(api_url):
135
"""Fetch data from API with time-based cache expiration."""
136
# Simulate API call
137
time.sleep(1)
138
return {"data": "api_result", "timestamp": time.time()}
139
140
# Use cached functions
141
data = load_data("data.csv")
142
api_result = fetch_api_data("https://api.example.com/data")
143
144
st.dataframe(data)
145
st.json(api_result)
146
```
147
148
### Modern Caching (Experimental)
149
150
New caching decorators with improved performance and features.
151
152
```python { .api }
153
@experimental_memo(persist: str = None, show_spinner: bool = True, suppress_st_warning: bool = False, max_entries: int = None, ttl: float = None)
154
def memo_function():
155
"""
156
Decorator for caching data and computations (experimental).
157
158
Parameters:
159
- persist: Persistence mode ("disk" or None)
160
- show_spinner: Whether to show spinner during computation
161
- suppress_st_warning: Whether to suppress Streamlit warnings
162
- max_entries: Maximum number of cache entries
163
- ttl: Time-to-live in seconds
164
"""
165
166
@experimental_singleton(show_spinner: bool = True, suppress_st_warning: bool = False)
167
def singleton_function():
168
"""
169
Decorator for creating singleton objects (experimental).
170
171
Parameters:
172
- show_spinner: Whether to show spinner during initialization
173
- suppress_st_warning: Whether to suppress Streamlit warnings
174
"""
175
```
176
177
#### Usage Example
178
179
```python
180
import streamlit as st
181
import pandas as pd
182
import numpy as np
183
184
@st.experimental_memo
185
def expensive_computation(n):
186
"""Expensive computation with memo caching."""
187
# Simulate heavy computation
188
result = np.random.rand(n, n).dot(np.random.rand(n, n))
189
return result
190
191
@st.experimental_singleton
192
def get_database_connection():
193
"""Create singleton database connection."""
194
# Simulate database connection setup
195
class MockDB:
196
def __init__(self):
197
self.connected = True
198
199
def query(self, sql):
200
return pd.DataFrame({"result": [1, 2, 3]})
201
202
return MockDB()
203
204
# Use modern caching
205
matrix = expensive_computation(100)
206
db = get_database_connection()
207
208
st.write(f"Matrix shape: {matrix.shape}")
209
st.dataframe(db.query("SELECT * FROM table"))
210
```
211
212
### Session State
213
214
Manage user session data that persists across app reruns.
215
216
```python { .api }
217
session_state: SessionStateProxy
218
# Access via st.session_state
219
220
class SessionStateProxy:
221
"""Session state management interface."""
222
223
def __getitem__(self, key: str) -> Any:
224
"""Get session state value."""
225
226
def __setitem__(self, key: str, value: Any) -> None:
227
"""Set session state value."""
228
229
def __contains__(self, key: str) -> bool:
230
"""Check if key exists in session state."""
231
232
def __delitem__(self, key: str) -> None:
233
"""Delete session state key."""
234
```
235
236
#### Usage Example
237
238
```python
239
import streamlit as st
240
241
# Initialize session state
242
if "counter" not in st.session_state:
243
st.session_state.counter = 0
244
245
if "user_data" not in st.session_state:
246
st.session_state.user_data = {}
247
248
# Use session state with widgets
249
col1, col2, col3 = st.columns(3)
250
251
with col1:
252
if st.button("Increment"):
253
st.session_state.counter += 1
254
255
with col2:
256
if st.button("Decrement"):
257
st.session_state.counter -= 1
258
259
with col3:
260
if st.button("Reset"):
261
st.session_state.counter = 0
262
263
st.write(f"Counter: {st.session_state.counter}")
264
265
# Form data persistence
266
with st.form("user_form"):
267
name = st.text_input("Name", value=st.session_state.user_data.get("name", ""))
268
age = st.number_input("Age", value=st.session_state.user_data.get("age", 0))
269
270
if st.form_submit_button("Save"):
271
st.session_state.user_data["name"] = name
272
st.session_state.user_data["age"] = age
273
st.success("Data saved to session!")
274
275
# Display all session state (for debugging)
276
with st.expander("Session State Debug"):
277
st.write(st.session_state)
278
```
279
280
### Secrets Management
281
282
Securely access application secrets and configuration.
283
284
```python { .api }
285
secrets: SecretsProxy
286
# Access via st.secrets
287
288
class SecretsProxy:
289
"""Secrets management interface."""
290
291
def __getitem__(self, key: str) -> Any:
292
"""Get secret value."""
293
294
def __contains__(self, key: str) -> bool:
295
"""Check if secret exists."""
296
```
297
298
#### Usage Example
299
300
```python
301
import streamlit as st
302
303
# Access secrets (configured in .streamlit/secrets.toml)
304
db_password = st.secrets["database"]["password"]
305
api_key = st.secrets["api_key"]
306
307
# Use secrets safely
308
if "database" in st.secrets:
309
connection_string = f"postgresql://user:{st.secrets.database.password}@localhost/db"
310
st.success("Database configured")
311
else:
312
st.error("Database secrets not found")
313
314
# Example secrets.toml structure:
315
st.code("""
316
# .streamlit/secrets.toml
317
api_key = "your-api-key-here"
318
319
[database]
320
host = "localhost"
321
port = 5432
322
username = "user"
323
password = "secret-password"
324
""", language="toml")
325
```
326
327
### App Control and Lifecycle
328
329
Control application execution flow and provide user feedback.
330
331
```python { .api }
332
def stop() -> NoReturn:
333
"""
334
Stop execution of the Streamlit script.
335
336
Raises:
337
StreamlitAPIException: Always (stops execution)
338
"""
339
340
def balloons() -> DeltaGenerator:
341
"""Display falling balloons animation."""
342
343
def snow() -> DeltaGenerator:
344
"""Display falling snow animation."""
345
346
def progress(value: float) -> DeltaGenerator:
347
"""
348
Display a progress bar.
349
350
Parameters:
351
- value: Progress value between 0.0 and 1.0
352
353
Returns:
354
DeltaGenerator: Progress bar object that can be updated
355
"""
356
357
def spinner(text: str = "In progress...") -> ContextManager[None]:
358
"""
359
Display a spinner with text during long operations.
360
361
Parameters:
362
- text: Text displayed next to spinner
363
364
Returns:
365
Context manager for use with 'with' statement
366
"""
367
368
def echo(code_location: str = "above") -> ContextManager[None]:
369
"""
370
Display code while executing it.
371
372
Parameters:
373
- code_location: Where to show code ("above" or "below")
374
375
Returns:
376
Context manager for code echoing
377
"""
378
```
379
380
#### Usage Example
381
382
```python
383
import streamlit as st
384
import time
385
386
# Celebration animations
387
if st.button("Celebrate!"):
388
st.balloons()
389
st.success("Congratulations!")
390
391
if st.button("Winter Theme"):
392
st.snow()
393
st.info("Let it snow!")
394
395
# Progress bar
396
progress_bar = st.progress(0)
397
status_text = st.empty()
398
399
for i in range(100):
400
progress_bar.progress(i + 1)
401
status_text.text(f'Progress: {i+1}%')
402
time.sleep(0.01)
403
404
status_text.text('Operation completed!')
405
406
# Spinner for long operations
407
with st.spinner('Loading data...'):
408
time.sleep(3) # Simulate long operation
409
data = [1, 2, 3, 4, 5]
410
411
st.success('Data loaded!')
412
st.write(data)
413
414
# Echo code execution
415
with st.echo():
416
# This code will be displayed and executed
417
x = 10
418
y = 20
419
result = x + y
420
st.write(f"The result is {result}")
421
422
# Conditional stop
423
user_input = st.text_input("Enter 'stop' to halt execution:")
424
if user_input.lower() == 'stop':
425
st.error("Execution stopped by user!")
426
st.stop()
427
428
st.write("This will only show if execution wasn't stopped")
429
```
430
431
### Query Parameters (Experimental)
432
433
Access and modify URL query parameters.
434
435
```python { .api }
436
def experimental_get_query_params() -> Dict[str, List[str]]:
437
"""
438
Get the current query parameters from the URL.
439
440
Returns:
441
Dictionary mapping parameter names to lists of values
442
"""
443
444
def experimental_set_query_params(**kwargs) -> None:
445
"""
446
Set query parameters in the URL.
447
448
Parameters:
449
- **kwargs: Parameter names and values to set
450
"""
451
```
452
453
#### Usage Example
454
455
```python
456
import streamlit as st
457
458
# Get current query parameters
459
query_params = st.experimental_get_query_params()
460
st.write("Current query parameters:", query_params)
461
462
# Use query parameters to set initial state
463
if "page" in query_params:
464
initial_page = query_params["page"][0]
465
else:
466
initial_page = "home"
467
468
# Widget that updates URL
469
page = st.selectbox("Select page:", ["home", "data", "settings"],
470
index=["home", "data", "settings"].index(initial_page))
471
472
# Update query parameters when selection changes
473
if page != initial_page:
474
st.experimental_set_query_params(page=page)
475
476
# Multiple parameters
477
filter_type = st.selectbox("Filter:", ["all", "active", "inactive"])
478
sort_by = st.selectbox("Sort by:", ["name", "date", "priority"])
479
480
# Update multiple parameters
481
st.experimental_set_query_params(
482
page=page,
483
filter=filter_type,
484
sort=sort_by
485
)
486
487
st.write(f"Current page: {page}")
488
st.write(f"Filter: {filter_type}, Sort: {sort_by}")
489
```
490
491
### Script Control (Experimental)
492
493
Programmatically control script execution flow.
494
495
```python { .api }
496
def experimental_rerun() -> NoReturn:
497
"""
498
Rerun the current script (experimental).
499
500
Raises:
501
StreamlitAPIException: Always (triggers rerun)
502
"""
503
```
504
505
#### Usage Example
506
507
```python
508
import streamlit as st
509
510
# Button that triggers rerun
511
if st.button("Refresh Data"):
512
# Clear any cached data if needed
513
st.cache.clear()
514
515
# Trigger script rerun
516
st.experimental_rerun()
517
518
# Conditional rerun based on state
519
if st.session_state.get("needs_refresh", False):
520
st.session_state.needs_refresh = False
521
st.experimental_rerun()
522
```
523
524
### User Information (Experimental)
525
526
Access user information in deployed apps.
527
528
```python { .api }
529
experimental_user: UserInfoProxy
530
531
class UserInfoProxy:
532
"""User information access interface (experimental)."""
533
534
@property
535
def email(self) -> str:
536
"""Get user's email address (if available)."""
537
```
538
539
#### Usage Example
540
541
```python
542
import streamlit as st
543
544
# Access user information (only works in deployed apps)
545
try:
546
user_email = st.experimental_user.email
547
st.write(f"Welcome, {user_email}!")
548
except:
549
st.write("User information not available (local development)")
550
551
# Conditional features based on user
552
if hasattr(st.experimental_user, 'email'):
553
if "@company.com" in st.experimental_user.email:
554
st.info("You have admin access")
555
admin_section = st.checkbox("Show admin panel")
556
if admin_section:
557
st.write("Admin controls would go here")
558
```
559
560
## Performance and Caching Best Practices
561
562
- Use `@st.cache` or `@st.experimental_memo` for expensive data loading
563
- Use `@st.experimental_singleton` for database connections and ML models
564
- Store user input in `st.session_state` to maintain state across reruns
565
- Use `st.secrets` for sensitive configuration data
566
- Set appropriate TTL values for time-sensitive cached data
567
- Use `suppress_st_warning=True` to silence caching warnings in production