pypi-streamlit

Description
A faster way to build and share data apps
Author
tessl
Last updated

How to use

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

configuration-control.md docs/

1
# Configuration and Control
2
3
Application configuration, execution control, and utility functions for managing app behavior, page settings, and runtime control flow.
4
5
## Capabilities
6
7
### Page Configuration
8
9
Configure global page settings, appearance, and metadata.
10
11
```python { .api }
12
def set_page_config(page_title=None, page_icon=None, layout="centered", initial_sidebar_state="auto", menu_items=None):
13
"""
14
Configure the default settings of the page.
15
16
Note: This must be called as the first Streamlit command in your script.
17
18
Parameters:
19
- page_title (str): The page title shown in browser tab
20
- page_icon (str): Emoji or image URL for the page favicon
21
- layout (str): Page layout ('centered' or 'wide')
22
- initial_sidebar_state (str): Initial sidebar state ('auto', 'expanded', 'collapsed')
23
- menu_items (dict): Custom menu items in the hamburger menu
24
25
Returns:
26
None
27
"""
28
```
29
30
### Execution Control
31
32
Control script execution flow and trigger reruns.
33
34
```python { .api }
35
def rerun():
36
"""
37
Rerun the script immediately.
38
39
Returns:
40
None (function does not return)
41
"""
42
43
def stop():
44
"""
45
Stop execution of the script immediately.
46
47
Returns:
48
None (function does not return)
49
"""
50
51
def switch_page(page):
52
"""
53
Programmatically switch to another page in a multipage app.
54
55
Parameters:
56
- page (str or Page): Page name or Page object to switch to
57
58
Returns:
59
None (function does not return)
60
"""
61
```
62
63
### Configuration Options
64
65
Get and set Streamlit configuration options.
66
67
```python { .api }
68
def get_option(key):
69
"""
70
Return the value of a given Streamlit config option.
71
72
Parameters:
73
- key (str): Configuration option key (e.g., 'theme.primaryColor')
74
75
Returns:
76
Any: Configuration option value
77
"""
78
79
def set_option(key, value):
80
"""
81
Set a Streamlit config option to the given value.
82
83
Parameters:
84
- key (str): Configuration option key
85
- value: Value to set for the configuration option
86
87
Returns:
88
None
89
"""
90
```
91
92
### Development and Debugging
93
94
Utilities for development, debugging, and code inspection.
95
96
```python { .api }
97
def echo(code_location="above"):
98
"""
99
Use in a `with` block to draw source code on the app, then execute it.
100
101
Parameters:
102
- code_location (str): Where to show code ('above' or 'below')
103
104
Returns:
105
ContextManager: Echo context manager
106
"""
107
108
def help(obj):
109
"""
110
Display the help string for an object (function, class, module, etc.).
111
112
Parameters:
113
- obj: Python object to show help for
114
115
Returns:
116
None
117
"""
118
```
119
120
### Branding and Identity
121
122
Add branding elements to your application.
123
124
```python { .api }
125
def logo(image, link=None, icon_image=None, size="medium"):
126
"""
127
Display a logo widget in the top-left corner of the app.
128
129
Parameters:
130
- image: Logo image (file path, URL, PIL Image, or bytes)
131
- link (str): URL to navigate to when logo is clicked
132
- icon_image: Small icon version of the logo for mobile/collapsed view
133
- size (str): Logo size ('small', 'medium', 'large')
134
135
Returns:
136
None
137
"""
138
```
139
140
### Context Information
141
142
Access runtime context and environment information.
143
144
```python { .api }
145
# Context information proxy
146
context: ContextProxy
147
148
# Access patterns:
149
# st.context.cookies # Browser cookies (if available)
150
# st.context.headers # HTTP headers (if available)
151
# st.context.query_params # URL query parameters
152
```
153
154
### Secrets Management
155
156
Securely access secrets and configuration values.
157
158
```python { .api }
159
# Secrets singleton for accessing secrets.toml and environment variables
160
secrets: SecretsProxy
161
162
# Access patterns:
163
# st.secrets["api_key"] # Access secret by key
164
# st.secrets.database.password # Access nested secrets
165
# st.secrets.has_key("key") # Check if secret exists
166
```
167
168
## Usage Examples
169
170
### Page Configuration
171
172
```python
173
import streamlit as st
174
175
# Must be first Streamlit command
176
st.set_page_config(
177
page_title="My Analytics App",
178
page_icon="πŸ“Š",
179
layout="wide",
180
initial_sidebar_state="expanded",
181
menu_items={
182
'Get Help': 'https://docs.streamlit.io',
183
'Report a bug': 'https://github.com/streamlit/streamlit/issues',
184
'About': "This is my custom analytics dashboard built with Streamlit!"
185
}
186
)
187
188
st.title("πŸ“Š Analytics Dashboard")
189
st.write("This app uses wide layout and custom page configuration.")
190
191
# Wide layout example
192
col1, col2, col3, col4 = st.columns(4)
193
194
with col1:
195
st.metric("Revenue", "$125K", "8%")
196
with col2:
197
st.metric("Users", "2.4K", "12%")
198
with col3:
199
st.metric("Sessions", "8.3K", "5%")
200
with col4:
201
st.metric("Bounce Rate", "32%", "-2%")
202
203
# Sample wide chart
204
import pandas as pd
205
import numpy as np
206
207
chart_data = pd.DataFrame(
208
np.random.randn(50, 4),
209
columns=['A', 'B', 'C', 'D']
210
)
211
212
st.subheader("Performance Over Time")
213
st.line_chart(chart_data)
214
```
215
216
### Execution Control
217
218
```python
219
# Rerun example
220
st.title("πŸ”„ Execution Control Demo")
221
222
# Counter with auto-increment
223
if 'counter' not in st.session_state:
224
st.session_state.counter = 0
225
226
st.write(f"Counter: {st.session_state.counter}")
227
228
col1, col2, col3, col4 = st.columns(4)
229
230
with col1:
231
if st.button("βž• Increment"):
232
st.session_state.counter += 1
233
st.rerun() # Immediately rerun to show updated counter
234
235
with col2:
236
if st.button("βž– Decrement"):
237
st.session_state.counter -= 1
238
st.rerun()
239
240
with col3:
241
if st.button("πŸ”„ Reset"):
242
st.session_state.counter = 0
243
st.rerun()
244
245
with col4:
246
if st.button("πŸ›‘ Stop"):
247
st.error("Execution stopped!")
248
st.stop() # This stops execution here
249
250
# This line won't execute if stop button was clicked
251
st.success("Script is still running!")
252
253
# Conditional execution control
254
if st.session_state.counter > 10:
255
st.warning("Counter is getting high!")
256
if st.button("Auto-reset counter"):
257
st.session_state.counter = 0
258
st.success("Counter has been reset!")
259
st.rerun()
260
261
if st.session_state.counter < 0:
262
st.info("Counter went negative, stopping execution.")
263
st.stop()
264
```
265
266
### Page Switching (Multipage App)
267
268
```python
269
# Define pages
270
def page_home():
271
st.title("🏠 Home")
272
st.write("Welcome to the home page!")
273
274
if st.button("Go to Analytics"):
275
st.switch_page("pages/analytics.py")
276
277
def page_analytics():
278
st.title("πŸ“Š Analytics")
279
st.write("Analytics page content")
280
281
if st.button("Go to Settings"):
282
st.switch_page("pages/settings.py")
283
284
def page_settings():
285
st.title("βš™οΈ Settings")
286
st.write("Settings page content")
287
288
if st.button("Go Home"):
289
st.switch_page("streamlit_app.py")
290
291
# For demonstration - normally these would be in separate files
292
current_page = st.radio("Simulate page:", ["Home", "Analytics", "Settings"])
293
294
if current_page == "Home":
295
page_home()
296
elif current_page == "Analytics":
297
page_analytics()
298
else:
299
page_settings()
300
```
301
302
### Configuration Management
303
304
```python
305
st.subheader("βš™οΈ Configuration Options")
306
307
# Display current theme colors
308
try:
309
primary_color = st.get_option('theme.primaryColor')
310
bg_color = st.get_option('theme.backgroundColor')
311
secondary_bg = st.get_option('theme.secondaryBackgroundColor')
312
text_color = st.get_option('theme.textColor')
313
314
st.write("**Current Theme Colors:**")
315
col1, col2 = st.columns(2)
316
317
with col1:
318
st.write(f"Primary Color: `{primary_color}`")
319
st.write(f"Background Color: `{bg_color}`")
320
321
with col2:
322
st.write(f"Secondary Background: `{secondary_bg}`")
323
st.write(f"Text Color: `{text_color}`")
324
325
except Exception as e:
326
st.info("Theme colors not configured or accessible")
327
328
# Server configuration
329
try:
330
server_port = st.get_option('server.port')
331
server_address = st.get_option('server.address')
332
333
st.write("**Server Configuration:**")
334
st.write(f"Port: `{server_port}`")
335
st.write(f"Address: `{server_address}`")
336
337
except Exception as e:
338
st.info("Server configuration not accessible")
339
340
# Development settings
341
st.write("**Development Options:**")
342
343
# Example of setting options (usually done in config.toml)
344
if st.button("Enable Development Mode"):
345
try:
346
st.set_option('logger.level', 'debug')
347
st.success("Development mode enabled!")
348
except Exception as e:
349
st.error(f"Could not set option: {e}")
350
```
351
352
### Code Echo and Documentation
353
354
```python
355
st.subheader("πŸ“ Code Echo Demo")
356
357
st.write("The code below will be displayed and then executed:")
358
359
# Echo code above execution
360
with st.echo():
361
import matplotlib.pyplot as plt
362
import numpy as np
363
364
# Generate sample data
365
x = np.linspace(0, 10, 100)
366
y = np.sin(x)
367
368
# Create plot
369
fig, ax = plt.subplots()
370
ax.plot(x, y)
371
ax.set_title('Sine Wave')
372
ax.set_xlabel('X values')
373
ax.set_ylabel('Y values')
374
375
# Display in Streamlit
376
st.pyplot(fig)
377
378
st.divider()
379
380
# Echo code below execution
381
st.write("Execute first, then show code:")
382
383
with st.echo(code_location="below"):
384
# This will execute first, then show the code
385
import pandas as pd
386
387
data = pd.DataFrame({
388
'A': [1, 2, 3, 4],
389
'B': [10, 20, 30, 40]
390
})
391
392
st.bar_chart(data.set_index('A'))
393
394
# Help example
395
st.subheader("πŸ†˜ Help Documentation")
396
397
col1, col2 = st.columns(2)
398
399
with col1:
400
st.write("**Help for built-in functions:**")
401
if st.button("Show help for st.write"):
402
st.help(st.write)
403
404
with col2:
405
st.write("**Help for Python objects:**")
406
if st.button("Show help for pandas.DataFrame"):
407
try:
408
import pandas as pd
409
st.help(pd.DataFrame)
410
except ImportError:
411
st.error("Pandas not available")
412
```
413
414
### Logo and Branding
415
416
```python
417
# Logo examples
418
st.subheader("🏷️ Logo and Branding")
419
420
# Set logo (normally done at top of app)
421
try:
422
st.logo(
423
"https://streamlit.io/images/brand/streamlit-logo-primary-colormark-darktext.png",
424
link="https://streamlit.io",
425
size="large"
426
)
427
st.success("Logo set successfully!")
428
except Exception as e:
429
st.info("Logo example (requires valid image URL)")
430
431
# Custom branding elements
432
st.markdown("""
433
<div style="
434
background: linear-gradient(90deg, #FF6B6B, #4ECDC4);
435
padding: 1rem;
436
border-radius: 0.5rem;
437
text-align: center;
438
color: white;
439
font-weight: bold;
440
margin: 1rem 0;
441
">
442
πŸš€ Custom Brand Header
443
</div>
444
""", unsafe_allow_html=True)
445
```
446
447
### Secrets Management
448
449
```python
450
st.subheader("πŸ” Secrets Management")
451
452
# Accessing secrets (create secrets.toml file in .streamlit folder)
453
try:
454
# Example secrets.toml structure:
455
# [database]
456
# host = "localhost"
457
# port = 5432
458
# username = "user"
459
# password = "secret"
460
461
# [api]
462
# key = "your-api-key"
463
# endpoint = "https://api.example.com"
464
465
st.write("**Available secrets:**")
466
467
# Check if secrets exist
468
if st.secrets.get("database"):
469
st.write("βœ… Database configuration found")
470
db_config = st.secrets["database"]
471
st.write(f"Database host: `{db_config.get('host', 'not set')}`")
472
st.write(f"Database port: `{db_config.get('port', 'not set')}`")
473
# Never display sensitive values like passwords
474
st.write("Password: `[HIDDEN]`")
475
else:
476
st.write("❌ Database configuration not found")
477
478
if st.secrets.get("api"):
479
st.write("βœ… API configuration found")
480
api_config = st.secrets["api"]
481
st.write(f"API endpoint: `{api_config.get('endpoint', 'not set')}`")
482
st.write("API key: `[HIDDEN]`")
483
else:
484
st.write("❌ API configuration not found")
485
486
except Exception as e:
487
st.info("No secrets file found. Create `.streamlit/secrets.toml` to use secrets.")
488
489
st.code("""
490
# Example .streamlit/secrets.toml file:
491
492
[database]
493
host = "localhost"
494
port = 5432
495
username = "myuser"
496
password = "mypassword"
497
498
[api]
499
key = "your-api-key-here"
500
endpoint = "https://api.example.com"
501
""")
502
503
# Environment variables as secrets
504
import os
505
506
st.write("**Environment Variables:**")
507
if os.getenv("STREAMLIT_ENV"):
508
st.write(f"Environment: `{os.getenv('STREAMLIT_ENV')}`")
509
else:
510
st.write("No STREAMLIT_ENV variable set")
511
512
# Safe secret usage pattern
513
def get_database_url():
514
try:
515
db_config = st.secrets["database"]
516
return f"postgresql://{db_config['username']}:{db_config['password']}@{db_config['host']}:{db_config['port']}/dbname"
517
except KeyError:
518
st.error("Database configuration incomplete")
519
return None
520
521
if st.button("Test Database Connection (Simulated)"):
522
db_url = get_database_url()
523
if db_url:
524
# In real app, you would use this URL to connect to database
525
st.success("Database URL generated successfully!")
526
st.write("Connection would be established with configured credentials")
527
else:
528
st.error("Could not generate database URL")
529
```
530
531
### Context Information
532
533
```python
534
st.subheader("🌐 Context Information")
535
536
# Query parameters from URL
537
st.write("**Query Parameters:**")
538
query_params = st.context.query_params if hasattr(st.context, 'query_params') else st.query_params
539
if query_params:
540
st.json(dict(query_params))
541
else:
542
st.write("No query parameters in URL")
543
544
# Headers (if available)
545
st.write("**Request Headers:**")
546
try:
547
if hasattr(st.context, 'headers'):
548
# Only show safe headers
549
safe_headers = ['user-agent', 'accept-language', 'accept-encoding']
550
headers_info = {k: v for k, v in st.context.headers.items() if k.lower() in safe_headers}
551
if headers_info:
552
st.json(headers_info)
553
else:
554
st.write("No safe headers to display")
555
else:
556
st.write("Headers not available in current context")
557
except Exception as e:
558
st.write("Headers not accessible")
559
560
# Session information
561
st.write("**Session Information:**")
562
session_info = {
563
"Session State Keys": list(st.session_state.keys()),
564
"Number of State Variables": len(st.session_state)
565
}
566
st.json(session_info)
567
```
568
569
### Advanced Configuration
570
571
```python
572
st.subheader("πŸ”§ Advanced Configuration")
573
574
# Performance monitoring
575
if st.button("Check Performance Settings"):
576
try:
577
# Check caching settings
578
cache_settings = {
579
"Cache Enabled": True, # Always enabled in current versions
580
"Max Cache Size": "Not directly accessible",
581
}
582
st.json(cache_settings)
583
584
# Memory usage (if available)
585
import psutil
586
process = psutil.Process()
587
memory_info = {
588
"Memory Usage (MB)": round(process.memory_info().rss / 1024 / 1024, 2),
589
"CPU Percent": f"{process.cpu_percent()}%"
590
}
591
st.json(memory_info)
592
593
except ImportError:
594
st.info("Install psutil for memory monitoring: `pip install psutil`")
595
except Exception as e:
596
st.error(f"Could not get performance info: {e}")
597
598
# Development utilities
599
if st.checkbox("Development Mode"):
600
st.warning("🚨 Development mode enabled")
601
602
# Show session state
603
with st.expander("Session State Debug"):
604
st.json(dict(st.session_state))
605
606
# Show configuration
607
with st.expander("App Configuration"):
608
config_info = {
609
"Python Path": __file__ if '__file__' in globals() else "Unknown",
610
"Streamlit Version": st.__version__,
611
}
612
st.json(config_info)
613
614
# Clear all caches
615
if st.button("🧹 Clear All Caches"):
616
st.cache_data.clear()
617
st.cache_resource.clear()
618
st.success("All caches cleared!")
619
```