Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 15 additions & 36 deletions .ai/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -699,40 +699,7 @@ Special handling for Colab:

### Dash() Constructor Parameters

**Basic Setup:**
- `name` - Application name (default: infers from `__name__`)
- `server` - Server instance (Flask, Quart, or FastAPI) or `True` to create Flask (default: `True`)
- `title` - Browser tab title (default: `"Dash"`)
- `update_title` - Title during callbacks (default: `"Updating..."`)

**Assets & Resources:**
- `assets_folder` - Path to assets directory (default: `"assets"`)
- `assets_url_path` - URL path for assets (default: `"assets"`)
- `assets_ignore` - Regex to exclude assets (default: `""`)
- `serve_locally` - Serve from local vs CDN (default: `True`)
- `external_scripts` - Additional JS URLs
- `external_stylesheets` - Additional CSS URLs

**Routing:**
- `url_base_pathname` - Base URL prefix for entire app
- `requests_pathname_prefix` - Prefix for AJAX requests
- `routes_pathname_prefix` - Prefix for API routes

**Multi-Page:**
- `use_pages` - Enable pages system (default: auto-detect)
- `pages_folder` - Path to pages directory (default: `"pages"`)

**Behavior:**
- `suppress_callback_exceptions` - Skip callback validation (default: `False`)
- `prevent_initial_callbacks` - Skip callbacks on load (default: `False`)
- `background_callback_manager` - DiskcacheManager or CeleryManager
- `on_error` - Global callback error handler
- `shared_storage` - Cross-process state + pub/sub backend (default: off). Pass `LocalSharedStorage` to enable, or a `BaseSharedStorage` subclass/instance to swap. See [Shared Storage](#shared-storage).

**WebSocket Callbacks:**
- `websocket_callbacks` - Enable WebSocket for all callbacks (default: `False`). Requires FastAPI backend.
- `websocket_allowed_origins` - List of allowed origins for WebSocket connections
- `websocket_inactivity_timeout` - Disconnect WebSocket after inactivity period in ms (default: `300000` = 5 minutes). Set to `0` to disable.
Read the `Dash.__init__` signature and docstring in `dash/dash.py`. They are the source of truth; a copied list here would drift.

### app.run() Parameters

Expand Down Expand Up @@ -1606,16 +1573,28 @@ Talisman(app.server, content_security_policy={

### Meta Tag Sanitization

Meta tag values are HTML-escaped to prevent injection:
`Dash.index()` builds the `<meta>` tags of the index page from three sources, in this order:

1. **Social media tags** (`_page_meta_tags` in `dash/_pages.py`): `description`, `twitter:*` and `og:*`. Added when `include_pages_meta=True` (the default) and the app uses pages or sets `description` or `image`. With pages, the matched page's `title`, `description` and `image` (from `register_page`) override the app values. `title` and `description` can be functions, called with the path variables. `image` is an asset filename or a URL; `image_url` on a page wins over both.
2. **Defaults** (`Dash._generate_meta`): `X-UA-Compatible`, `charset` and `viewport`. Each is skipped when `meta_tags` already has one, so `meta_tags=[{"name": "viewport", ...}]` replaces the default.
3. **`meta_tags`** from the constructor, as given.

Duplicates are not merged: a `description` in `meta_tags` is emitted next to the generated one, not instead of it.

Every tag goes through `format_tag(..., sanitize=True)` in `dash/_utils.py`, which runs attribute values through `html.escape` (quotes included), so a value cannot close the attribute or inject markup. Attribute names are not escaped and must come from trusted code. This covers `register_page` values and `twitter:url`, which is the request URL. `index_string` and `index` hooks run after this step and are not sanitized.

```python
app = Dash(__name__, meta_tags=[
{"name": "description", "content": "Safe <content>"}
{"name": "description", "content": 'Safe "<content>"'}
])
# <meta name="description" content="Safe &quot;&lt;content&gt;&quot;">
```

Tests: `test_inin005` to `test_inin007` in `tests/integration/test_integration.py`, `test_pala002`/`test_pala003` in `tests/integration/multi_page/test_pages_layout.py`.

### Key Files

- `dash/dash-renderer/src/utils/clientsideFunctions.ts` - URL sanitization (`clean_url`)
- `dash/dash.py:csp_hashes()` - CSP hash generation
- `dash/_utils.py:format_tag()` - Meta tag escaping
- `tests/integration/security/` - Security test coverage
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).
## [UNRELEASED]

### Fixed
- [#4196](https://github.com/plotly/dash/pull/4196) Fix `use_pages=True` crashing with `AttributeError` in Jupyter, where the `__main__` module has no `__file__`. Fixes [#3132](https://github.com/plotly/dash/issues/3132).
- [#4196](https://github.com/plotly/dash/pull/4196) Fix pages `redirect_from` returning 404 behind a proxy that strips `requests_pathname_prefix` (Dash Enterprise workspaces), and redirecting to a doubled prefix with `url_base_pathname`. Fixes [#3549](https://github.com/plotly/dash/issues/3549).
- [#4167](https://github.com/plotly/dash/pull/4167) `dash-generate-components` no longer crashes when generating an R package from a `package.json` whose `author` is an object or includes a URL, and a missing author email now gets the intended error message. Fixes [#1577](https://github.com/plotly/dash/issues/1577).
- [#4169](https://github.com/plotly/dash/pull/4169) Fix the inferred path of a page whose module name contains the pages folder name: `pages/landing_pages.py` no longer gets `/` and `pages/subpages/report.py` no longer gets `/report`. Fixes [#4168](https://github.com/plotly/dash/issues/4168).
- [#4174](https://github.com/plotly/dash/pull/4174) Fix `dcc.Graph` discarding earlier layout changes when multiple `Plotly.relayout` calls run before React delivers the updated figure prop. Fixes [#4172](https://github.com/plotly/dash/issues/4172).
Expand Down
176 changes: 159 additions & 17 deletions dash/_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,32 @@ def __call__(self, *args, **kwargs):


class _Hooks:
"""
Extend every Dash app from a separate package, through ``dash.hooks``.

Hooks are registered at import time, usually in a plugin package, and
apply to every ``Dash`` app created after they are registered. To load a
plugin without importing it in the app, declare a ``dash_hooks`` entry
point that points to the module registering the hooks::

# pyproject.toml
[project.entry-points.dash_hooks]
my_plugin = "my_plugin"

Example::

from dash import hooks, html

@hooks.layout()
def add_footer(layout):
return [layout, html.Footer("Powered by my_plugin")]

Decorator hooks take ``priority`` and ``final``. Hooks with a higher
``priority`` run first; without one, hooks run in the order they were
registered. A ``final`` hook always runs last, and only one ``final``
hook is allowed per hook type.
"""

def __init__(self) -> None:
self._ns: _t.Dict[str, _t.List[_t.Any]] = {
"setup": [],
Expand Down Expand Up @@ -94,8 +120,17 @@ def get_hooks(self, hook: str) -> _t.List[_Hook]:

def layout(self, priority: _t.Optional[int] = None, final: bool = False):
"""
Run a function when serving the layout, the return value
will be used as the layout.
Modify the layout each time it is served.

The function receives the current layout and returns the new one.
Layout hooks are chained, each one receives the result of the
previous one.

Example::

@hooks.layout()
def wrap(layout):
return html.Div([html.Header("My org"), layout])
"""

def _wrap(func: _t.Callable[[LayoutType], LayoutType]):
Expand All @@ -106,7 +141,17 @@ def _wrap(func: _t.Callable[[LayoutType], LayoutType]):

def setup(self, priority: _t.Optional[int] = None, final: bool = False):
"""
Can be used to get a reference to the app after it is instantiated.
Run a function with the app instance once it is created.

Called during ``Dash.__init__``, before the server routes are set
up, with the ``Dash`` app as its only argument. The return value is
ignored.

Example::

@hooks.setup()
def on_setup(app):
app.config.suppress_callback_exceptions = True
"""

def _setup(func: _t.Callable[[Dash], None]):
Expand All @@ -125,9 +170,20 @@ def route(
"""
Add a route to the Dash server.

The route function can be `async def`; with the Flask backend this
requires `flask[async]`. Read the request with
`dash.get_app().backend.request_adapter()`.
``name`` is the url path, relative to ``routes_pathname_prefix``. It
defaults to the function name. ``methods`` lists the allowed HTTP
methods. The function takes no arguments and its return value is
the response.

The route function can be ``async def``; with the Flask backend this
requires ``flask[async]``. Read the request with
``dash.get_app().backend.request_adapter()``.

Example::

@hooks.route("my-plugin/status", methods=("GET",))
def status():
return {"ok": True}
"""

def wrap(func: _t.Callable[[], _t.Any]):
Expand All @@ -144,7 +200,20 @@ def wrap(func: _t.Callable[[], _t.Any]):
return wrap

def error(self, priority: _t.Optional[int] = None, final: bool = False):
"""Automatically add an error handler to the dash app."""
"""
Handle exceptions raised in callbacks.

The function receives the exception, the same way as the app
``on_error`` argument. It runs after the app ``on_error`` handler
if one is set. A value returned by either is used as the callback
output, the app handler result taking precedence.

Example::

@hooks.error()
def log_error(err):
logger.exception(err)
"""

def _error(func: _t.Callable[[Exception], _t.Any]):
self.add_hook("error", func, priority=priority, final=final)
Expand All @@ -156,7 +225,16 @@ def callback(
self, *args, priority: _t.Optional[int] = None, final: bool = False, **kwargs
):
"""
Add a callback to all the apps with the hook installed.
Add a callback to every app.

Takes the same arguments as ``dash.callback``. The components it
uses must be in the app layout, usually added with a layout hook.

Example::

@hooks.callback(Output("plugin-out", "children"), Input("plugin-btn", "n_clicks"))
def on_click(n_clicks):
return f"Clicked {n_clicks} times"
"""

def wrap(func):
Expand All @@ -175,20 +253,61 @@ def clientside_callback(
self, clientside_function: ClientsideFuncType, *args, **kwargs
):
"""
Add a callback to all the apps with the hook installed.
Add a clientside callback to every app.

Takes the same arguments as ``dash.clientside_callback``. Unlike
the other hooks, this is a plain call, not a decorator.

Example::

hooks.clientside_callback(
"function(n) { return n || 0; }",
Output("plugin-count", "children"),
Input("plugin-btn", "n_clicks"),
)
"""
self._clientside_callbacks.append((clientside_function, args, kwargs))

def script(self, distribution: _t.List[ResourceType]):
"""Add js scripts to the page."""
"""
Add JavaScript files to every app.

``distribution`` is a list of resources in the same format as a
component library ``_js_dist``: dicts with ``relative_package_path``,
``external_url``, ``namespace``, and so on.

Example::

hooks.script([{
"external_url": "https://cdn.example.com/plugin.js",
"namespace": "my_plugin",
}])
"""
self._js_dist.extend(distribution)

def stylesheet(self, distribution: _t.List[ResourceType]):
"""Add stylesheets to the page."""
"""
Add stylesheets to every app.

``distribution`` is a list of resources in the same format as a
component library ``_css_dist``. See ``hooks.script``.
"""
self._css_dist.extend(distribution)

def index(self, priority: _t.Optional[int] = None, final=False):
"""Modify the index of the apps."""
"""
Modify the HTML of the index page.

The function receives the rendered index as a string and returns
the new one. The result must still contain the Dash entry points,
or serving the page raises an error.

Example::

@hooks.index()
def add_banner(index):
return index.replace("<body>", "<body><div>Beta</div>")
"""

def wrap(func):
self.add_hook(
Expand All @@ -205,10 +324,21 @@ def custom_data(
self, namespace: str, priority: _t.Optional[int] = None, final=False
):
"""
Add data to the callback_context.custom_data property under the namespace.
Add data to ``callback_context.custom_data`` under ``namespace``.

Runs before each callback. The function receives the callback
context value and its return value is stored under ``namespace``.
It runs inside the request, so it can read it with
``dash.get_app().backend.request_adapter()``.

The hook function takes the current context_value and before the ctx is set
and has access to the flask request context.
Example::

@hooks.custom_data("auth")
def user(_ctx):
req = dash.get_app().backend.request_adapter()
return {"user": req.headers.get("X-User")}

# in a callback: ctx.custom_data.auth["user"]
"""

def wrap(func: _t.Callable[[_t.Dict], _t.Any]):
Expand All @@ -233,11 +363,23 @@ def devtool(
"""
Add a component to be rendered inside the dev tools.

``namespace`` and ``component_type`` name the component, as in its
``_namespace`` and ``_type``. ``position`` is ``"right"`` or
``"left"`` in the dev tools bar. Only shown when the dev tools UI is
on (``debug=True``).

If it's a dash component, it can be used in callbacks provided
that it has an id and the dependency is set with allow_optional=True.
that it has an id and the dependency is set with ``allow_optional=True``.

`props` can be a function, in which case it will be called before
``props`` can be a function, in which case it will be called before
sending the component to the frontend.

Example::

hooks.devtool(
"dash_html_components", "Div",
props={"id": "plugin-devtool", "children": "my_plugin"},
)
"""
self._ns["dev_tools"].append(
{
Expand Down
12 changes: 7 additions & 5 deletions dash/_pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from . import _validate
from ._callback_context import context_value
from ._get_app import get_app
from ._get_paths import get_relative_path
from ._get_paths import app_get_relative_path, get_relative_path
from ._utils import AttributeDict, get_root_path

CONFIG = AttributeDict()
Expand Down Expand Up @@ -88,8 +88,8 @@ def _infer_path(module_name, template):
def _module_name_is_package(module_name):
if module_name not in sys.modules:
return False
file = sys.modules[module_name].__file__
return file and file.endswith("__init__.py")
file = getattr(sys.modules[module_name], "__file__", None)
return bool(file) and file.endswith("__init__.py")


def _path_to_module_name(path):
Expand Down Expand Up @@ -158,8 +158,10 @@ def _set_redirect(redirect_from, path):
app = get_app()
if redirect_from and len(redirect_from):
for redirect in redirect_from:
fullname = app.get_relative_path(redirect)
app.backend.add_redirect_rule(app, fullname, app.get_relative_path(path))
fullname = app_get_relative_path(
app.config.routes_pathname_prefix, redirect
)
app.backend.add_redirect_rule(app, fullname, path)


def register_page(
Expand Down
23 changes: 23 additions & 0 deletions tests/integration/multi_page/test_pages_layout.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import sys
import types

import pytest
import dash
from dash import Dash, Input, State, dcc, html, Output
Expand Down Expand Up @@ -295,3 +298,23 @@ def test_pala007_app_title_discription(dash_duo, clear_pages_state):
assert dash.page_registry["page1"]["title"] == "Page 1 Title"
assert dash.page_registry["home"]["description"] == "App Description"
assert dash.page_registry["page1"]["description"] == "Page 1 Description"


def test_pala008_main_module_without_file(
dash_duo, clear_pages_state, tmp_path, monkeypatch
):
# Jupyter runs the app in a __main__ module that has no __file__.
monkeypatch.setitem(sys.modules, "__main__", types.ModuleType("__main__"))
pages_folder = tmp_path / "pages"
pages_folder.mkdir()
(pages_folder / "home.py").write_text(
"import dash\n"
"from dash import html\n"
"dash.register_page(__name__, path='/')\n"
"layout = html.Div('home', id='home')\n"
)

app = Dash("__main__", use_pages=True, pages_folder=str(pages_folder))
app.layout = dash.page_container
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#home", "home")
Loading
Loading