Python web application framework for building reactive analytical web apps without JavaScript
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Dash provides comprehensive asset management for static files, external resources, and URL generation. Assets include CSS stylesheets, JavaScript files, images, and other static resources.
Generate URLs for static assets with automatic fingerprinting and cache busting.
def get_asset_url(path: str) -> str:
"""
Generate URL for asset file in the assets folder.
Parameters:
- path: Relative path to asset file within assets folder
Returns:
- Full URL to the asset with cache-busting parameters
"""Handle URL paths and routing within Dash applications.
def get_relative_path(path: str) -> str:
"""
Get relative path from the current request.
Parameters:
- path: Full or absolute path
Returns:
- Relative path from application root
"""
def strip_relative_path(path: str) -> str:
"""
Remove relative path prefix from URL.
Parameters:
- path: Path with potential relative prefix
Returns:
- Path with relative prefix removed
"""Configure external CSS and JavaScript resources for the application.
# External resource configuration
external_stylesheets = [
'https://codepen.io/chriddyp/pen/bWLwgP.css',
{
'href': 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css',
'rel': 'stylesheet',
'integrity': 'sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO',
'crossorigin': 'anonymous'
}
]
external_scripts = [
'https://code.jquery.com/jquery-3.6.0.min.js',
{
'src': 'https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js',
'integrity': 'sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p',
'crossorigin': 'anonymous'
}
]Automatic loading of assets from the assets folder with development hot reloading.
# Asset folder configuration
app = Dash(
__name__,
assets_folder='assets', # Assets directory path
assets_url_path='/assets/', # URL path for assets
assets_ignore='.*ignored.*' # Regex pattern to ignore files
)Project structure:
app.py
assets/
├── style.css
├── script.js
├── logo.png
└── data/
└── sample.jsonapp.py:
from dash import Dash, html, dcc
app = Dash(__name__)
app.layout = html.Div([
# CSS and JS automatically loaded from assets/
html.Img(src=app.get_asset_url('logo.png')),
html.H1("My Dash App"),
# Reference asset in component
html.Div(id="data-container"),
# Load data file
dcc.Store(
id='data-store',
data=app.get_asset_url('data/sample.json')
)
])assets/style.css:
/* Automatically loaded */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}
#data-container {
background-color: #f0f0f0;
padding: 10px;
border-radius: 5px;
}from dash import Dash, html
# External resources
external_stylesheets = [
# CDN stylesheet
'https://codepen.io/chriddyp/pen/bWLwgP.css',
# Bootstrap with integrity checking
{
'href': 'https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css',
'rel': 'stylesheet',
'integrity': 'sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3',
'crossorigin': 'anonymous'
}
]
external_scripts = [
# jQuery
'https://code.jquery.com/jquery-3.6.0.min.js',
# Custom external script
{
'src': 'https://example.com/custom-script.js',
'defer': True
}
]
app = Dash(
__name__,
external_stylesheets=external_stylesheets,
external_scripts=external_scripts
)
app.layout = html.Div([
html.H1("App with External Resources", className="display-4"),
html.P("Bootstrap styling applied!", className="lead")
])from dash import Dash, html, dcc, callback, Input, Output
import json
import os
app = Dash(__name__)
app.layout = html.Div([
dcc.Dropdown(
id='theme-selector',
options=[
{'label': 'Light Theme', 'value': 'light'},
{'label': 'Dark Theme', 'value': 'dark'},
{'label': 'Blue Theme', 'value': 'blue'}
],
value='light'
),
html.Div(id='dynamic-content')
])
@callback(
Output('dynamic-content', 'children'),
Input('theme-selector', 'value')
)
def load_theme_assets(theme):
# Load theme-specific data
data_file = f'assets/themes/{theme}-config.json'
if os.path.exists(data_file):
with open(data_file) as f:
theme_config = json.load(f)
else:
theme_config = {'name': theme, 'colors': {}}
return html.Div([
html.H2(f"{theme_config['name']} Theme Active"),
html.Img(src=app.get_asset_url(f'themes/{theme}-logo.png')),
html.Link(
rel='stylesheet',
href=app.get_asset_url(f'themes/{theme}.css')
)
])from dash import Dash, html
app = Dash(__name__)
# Enable asset fingerprinting for production
app.config.update({
'compress': True, # Enable gzip compression
'serve_locally': True # Serve assets locally vs CDN
})
app.layout = html.Div([
# Assets get fingerprinted URLs like: /assets/style.css?v=1.0.0
html.Img(src=app.get_asset_url('logo.png')),
# Multiple asset references
html.Div([
html.Img(src=app.get_asset_url('icons/home.svg')),
html.Img(src=app.get_asset_url('icons/user.svg')),
html.Img(src=app.get_asset_url('icons/settings.svg'))
])
])Using SASS preprocessing:
assets/style.scss:
$primary-color: #007bff;
$secondary-color: #6c757d;
.dashboard {
.header {
background-color: $primary-color;
padding: 1rem;
h1 {
color: white;
margin: 0;
}
}
.content {
padding: 2rem;
background-color: lighten($secondary-color, 40%);
}
}app.py:
from dash import Dash, html
# SASS files automatically compiled to CSS in assets/
app = Dash(__name__)
app.layout = html.Div([
html.Div([
html.H1("Dashboard")
], className="header"),
html.Div([
html.P("Dashboard content here...")
], className="content")
], className="dashboard")from dash import Dash, html
import os
class CustomDash(Dash):
def get_asset_url(self, path):
# Custom asset URL logic
if path.startswith('images/'):
# Serve images from CDN
return f"https://cdn.example.com/{path}"
elif path.endswith('.css'):
# Add version parameter to CSS files
version = os.path.getmtime(f"assets/{path}")
return f"/assets/{path}?v={version}"
else:
# Default behavior
return super().get_asset_url(path)
app = CustomDash(__name__)
app.layout = html.Div([
html.Img(src=app.get_asset_url('images/banner.jpg')), # From CDN
# CSS will have version parameter
])Project structure:
app.py
assets/
├── global.css
├── components/
│ ├── navbar.css
│ └── footer.css
└── pages/
├── home.css
├── analytics.css
└── settings.csspages/analytics.py:
import dash
from dash import html, dcc
dash.register_page(__name__, path='/analytics')
def layout():
return html.Div([
# Page-specific styling automatically loaded
html.Link(
rel='stylesheet',
href=dash.get_asset_url('pages/analytics.css')
),
html.H1("Analytics Dashboard"),
# Page content...
])AssetPath = str # Path to asset file
AssetURL = str # Generated asset URL
ExternalResource = Union[str, Dict[str, str]] # External resource specification
ResourceList = List[ExternalResource] # List of external resourcesInstall with Tessl CLI
npx tessl i tessl/pypi-dash