diff --git a/.github/workflows/testing.yml b/.github/workflows/testing.yml index 76b749b971..7184c7a477 100644 --- a/.github/workflows/testing.yml +++ b/.github/workflows/testing.yml @@ -17,6 +17,7 @@ jobs: # This output will be 'true' if files in the 'table_related_paths' list changed, 'false' otherwise. table_paths_changed: ${{ steps.filter.outputs.table_related_paths }} background_cb_changed: ${{ steps.filter.outputs.background_paths }} + backend_cb_changed: ${{ steps.filter.outputs.backend_paths }} steps: - name: Checkout repository uses: actions/checkout@v4 @@ -37,6 +38,9 @@ jobs: - 'tests/background_callback/**' - 'tests/async_tests/**' - 'requirements/**' + backend_paths: + - 'dash/backends/**' + - 'tests/backend_tests/**' build: name: Build Dash Package @@ -270,6 +274,109 @@ jobs: cd bgtests pytest --headless --nopercyfinalize tests/async_tests -v -s + backend-tests: + name: Run Backend Callback Tests (Python ${{ matrix.python-version }}) + needs: [build, changes_filter] + if: | + (github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/dev')) || + needs.changes_filter.outputs.backend_cb_changed == 'true' + timeout-minutes: 30 + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.9", "3.12"] + + services: + redis: + image: redis:6 + ports: + - 6379:6379 + options: >- + --health-cmd "redis-cli ping" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + + env: + REDIS_URL: redis://localhost:6379 + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'npm' + + - name: Install Node.js dependencies + run: npm ci + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + cache: 'pip' + + - name: Download built Dash packages + uses: actions/download-artifact@v4 + with: + name: dash-packages + path: packages/ + + - name: Install Dash packages + run: | + python -m pip install --upgrade pip wheel + python -m pip install "setuptools<78.0.0" + python -m pip install "selenium==4.32.0" + find packages -name dash-*.whl -print -exec sh -c 'pip install "{}[async,ci,testing,dev,celery,diskcache,fastapi,quart]"' \; + + - name: Install Google Chrome + run: | + sudo apt-get update + sudo apt-get install -y google-chrome-stable + + - name: Install ChromeDriver + run: | + echo "Determining Chrome version..." + CHROME_BROWSER_VERSION=$(google-chrome --version) + echo "Installed Chrome Browser version: $CHROME_BROWSER_VERSION" + CHROME_MAJOR_VERSION=$(echo "$CHROME_BROWSER_VERSION" | cut -f 3 -d ' ' | cut -f 1 -d '.') + echo "Detected Chrome Major version: $CHROME_MAJOR_VERSION" + if [ "$CHROME_MAJOR_VERSION" -ge 115 ]; then + echo "Fetching ChromeDriver version for Chrome $CHROME_MAJOR_VERSION using CfT endpoint..." + CHROMEDRIVER_VERSION_STRING=$(curl -sS "https://googlechromelabs.github.io/chrome-for-testing/LATEST_RELEASE_${CHROME_MAJOR_VERSION}") + if [ -z "$CHROMEDRIVER_VERSION_STRING" ]; then + echo "Could not automatically find ChromeDriver version for Chrome $CHROME_MAJOR_VERSION via LATEST_RELEASE. Please check CfT endpoints." + exit 1 + fi + CHROMEDRIVER_URL="https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/${CHROMEDRIVER_VERSION_STRING}/linux64/chromedriver-linux64.zip" + else + echo "Fetching ChromeDriver version for Chrome $CHROME_MAJOR_VERSION using older method..." + CHROMEDRIVER_VERSION_STRING=$(curl -sS "https://chromedriver.storage.googleapis.com/LATEST_RELEASE_${CHROME_MAJOR_VERSION}") + CHROMEDRIVER_URL="https://chromedriver.storage.googleapis.com/${CHROMEDRIVER_VERSION_STRING}/chromedriver_linux64.zip" + fi + echo "Using ChromeDriver version string: $CHROMEDRIVER_VERSION_STRING" + echo "Downloading ChromeDriver from: $CHROMEDRIVER_URL" + wget -q -O chromedriver.zip "$CHROMEDRIVER_URL" + unzip -o chromedriver.zip -d /tmp/ + sudo mv /tmp/chromedriver-linux64/chromedriver /usr/local/bin/chromedriver || sudo mv /tmp/chromedriver /usr/local/bin/chromedriver + sudo chmod +x /usr/local/bin/chromedriver + echo "/usr/local/bin" >> $GITHUB_PATH + shell: bash + + - name: Build/Setup test components + run: npm run setup-tests.py + + - name: Run Backend Callback Tests + run: | + mkdir bgtests + cp -r tests bgtests/tests + cd bgtests + touch __init__.py + pytest --headless --nopercyfinalize tests/backend_tests -v -s + table-unit: name: Table Unit/Lint Tests (Python ${{ matrix.python-version }}) needs: [build, changes_filter] diff --git a/.gitignore b/.gitignore index 89029448fe..06e855e2dc 100644 --- a/.gitignore +++ b/.gitignore @@ -93,3 +93,4 @@ packages/ !components/dash-core-components/tests/integration/upload/upload-assets/upft001.csv !components/dash-table/tests/assets/*.csv !components/dash-table/tests/selenium/assets/*.csv +dash_config.json diff --git a/components/dash-core-components/package.json b/components/dash-core-components/package.json index 79a35daaac..5e0d271c3f 100644 --- a/components/dash-core-components/package.json +++ b/components/dash-core-components/package.json @@ -125,6 +125,6 @@ "react-dom": "16 - 19" }, "browserslist": [ - "last 9 years and not dead" + "last 10 years and not dead" ] } diff --git a/components/dash-core-components/tests/integration/input/conftest.py b/components/dash-core-components/tests/integration/input/conftest.py index c03087db1a..f612cfe462 100644 --- a/components/dash-core-components/tests/integration/input/conftest.py +++ b/components/dash-core-components/tests/integration/input/conftest.py @@ -2,7 +2,7 @@ from dash import Dash, Input, Output, dcc, html -@pytest.fixture(scope="module") +@pytest.fixture def ninput_app(): app = Dash(__name__) app.layout = html.Div( @@ -35,7 +35,7 @@ def render(fval, tval): yield app -@pytest.fixture(scope="module") +@pytest.fixture def input_range_app(): app = Dash(__name__) app.layout = html.Div( @@ -59,7 +59,7 @@ def range_out(val): yield app -@pytest.fixture(scope="module") +@pytest.fixture def debounce_text_app(): app = Dash(__name__) app.layout = html.Div( @@ -89,7 +89,7 @@ def render(slow_val, fast_val): yield app -@pytest.fixture(scope="module") +@pytest.fixture def debounce_number_app(): app = Dash(__name__) app.layout = html.Div( diff --git a/components/dash-core-components/tests/integration/input/test_number_input.py b/components/dash-core-components/tests/integration/input/test_number_input.py index 01deb79287..e2ec647c69 100644 --- a/components/dash-core-components/tests/integration/input/test_number_input.py +++ b/components/dash-core-components/tests/integration/input/test_number_input.py @@ -238,6 +238,7 @@ def update_output(val): def test_inni010_valid_numbers(dash_dcc, ninput_app): dash_dcc.start_server(ninput_app) + elem = dash_dcc.wait_for_element("#input_false") for num, op in ( ("1.0", lambda x: int(float(x))), # limitation of js/json ("10e10", lambda x: int(float(x))), @@ -245,7 +246,7 @@ def test_inni010_valid_numbers(dash_dcc, ninput_app): (str(sys.float_info.max), float), (str(sys.float_info.min), float), ): - elem = dash_dcc.find_element("#input_false") + elem = dash_dcc.wait_for_element("#input_false") elem.send_keys(num) assert dash_dcc.wait_for_text_to_equal( "#div_false", str(op(num)) diff --git a/dash/_callback.py b/dash/_callback.py index 3785df7166..0ce4ee59a4 100644 --- a/dash/_callback.py +++ b/dash/_callback.py @@ -1,11 +1,8 @@ +from typing import Callable, Optional, Any, List, Tuple, Union, Dict +from functools import wraps import collections import hashlib import inspect -from functools import wraps - -from typing import Callable, Optional, Any, List, Tuple, Union, Dict - -import flask from .dependencies import ( handle_callback_args, @@ -38,10 +35,11 @@ clean_property_name, ) -from . import _validate from .background_callback.managers import BaseBackgroundCallbackManager from ._callback_context import context_value from ._no_update import NoUpdate +from . import _validate +from . import backends async def _async_invoke_callback( @@ -278,7 +276,7 @@ def insert_callback( no_output=False, optional=False, hidden=None, -): +) -> str: if prevent_initial_call is None: prevent_initial_call = config_prevent_initial_callbacks @@ -359,7 +357,7 @@ def _initialize_context(args, kwargs, inputs_state_indices, has_output, insert_o def _get_callback_manager( kwargs: dict, background: dict -) -> Union[BaseBackgroundCallbackManager, None]: +) -> BaseBackgroundCallbackManager: """Set up the background callback and manage jobs.""" callback_manager = background.get( "manager", kwargs.get("background_callback_manager", None) @@ -375,7 +373,8 @@ def _get_callback_manager( " and store results on redis.\n" ) - old_job = flask.request.args.getlist("oldJob") + adapter = backends.backend.request_adapter() + old_job = adapter.args.getlist("oldJob") if hasattr(adapter.args, "getlist") else [] if old_job: for job in old_job: @@ -389,6 +388,8 @@ def _setup_background_callback( ): """Set up the background callback and manage jobs.""" callback_manager = _get_callback_manager(kwargs, background) + if not callback_manager: + return to_json({"error": "No background callback manager configured"}) progress_outputs = background.get("progress") @@ -396,14 +397,11 @@ def _setup_background_callback( cache_key = callback_manager.build_cache_key( func, - # Inputs provided as dict is kwargs. func_args if func_args else func_kwargs, background.get("cache_args_to_ignore", []), None if cache_ignore_triggered else callback_ctx.get("triggered_inputs", []), ) - job_fn = callback_manager.func_registry.get(background_key) - ctx_value = AttributeDict(**context_value.get()) ctx_value.ignore_register_page = True ctx_value.pop("background_callback_manager") @@ -435,7 +433,8 @@ def _setup_background_callback( def _progress_background_callback(response, callback_manager, background): progress_outputs = background.get("progress") - cache_key = flask.request.args.get("cacheKey") + adapter = backends.backend.request_adapter() + cache_key = adapter.args.get("cacheKey") if progress_outputs: # Get the progress before the result as it would be erased after the results. @@ -452,8 +451,9 @@ def _update_background_callback( """Set up the background callback and manage jobs.""" callback_manager = _get_callback_manager(kwargs, background) - cache_key = flask.request.args.get("cacheKey") - job_id = flask.request.args.get("job") + adapter = backends.backend.request_adapter() + cache_key = adapter.args.get("cacheKey") if adapter else None + job_id = adapter.args.get("job") if adapter else None _progress_background_callback(response, callback_manager, background) @@ -473,8 +473,9 @@ def _handle_rest_background_callback( multi, has_update=False, ): - cache_key = flask.request.args.get("cacheKey") - job_id = flask.request.args.get("job") + adapter = backends.backend.request_adapter() + cache_key = adapter.args.get("cacheKey") if adapter else None + job_id = adapter.args.get("job") if adapter else None # Must get job_running after get_result since get_results terminates it. job_running = callback_manager.job_running(job_id) if not job_running and output_value is callback_manager.UNDEFINED: @@ -687,11 +688,11 @@ def add_context(*args, **kwargs): ) response: dict = {"multi": True} # type: ignore - - jsonResponse = None + jsonResponse: Optional[str] = None try: if background is not None: - if not flask.request.args.get("cacheKey"): + adapter = backends.backend.request_adapter() + if not (adapter and adapter.args.get("cacheKey")): return _setup_background_callback( kwargs, background, @@ -762,7 +763,8 @@ async def async_add_context(*args, **kwargs): try: if background is not None: - if not flask.request.args.get("cacheKey"): + adapter = backends.backend.request_adapter() + if not (adapter and adapter.args.get("cacheKey")): return _setup_background_callback( kwargs, background, diff --git a/dash/_callback_context.py b/dash/_callback_context.py index 09faf6f9a3..10cfb20055 100644 --- a/dash/_callback_context.py +++ b/dash/_callback_context.py @@ -4,9 +4,8 @@ import contextvars import typing -import flask - from . import exceptions +from . import backends from ._utils import AttributeDict, stringify_id @@ -222,14 +221,15 @@ def record_timing(name, duration, description=None): :param description: A description of the resource. :type description: string or None """ - timing_information = getattr(flask.g, "timing_information", {}) + request = backends.backend.request_adapter() + timing_information = getattr(request.context, "timing_information", {}) if name in timing_information: raise KeyError(f'Duplicate resource name "{name}" found.') timing_information[name] = {"dur": round(duration * 1000), "desc": description} - setattr(flask.g, "timing_information", timing_information) + setattr(request.context, "timing_information", timing_information) @property @has_context @@ -252,7 +252,8 @@ def using_outputs_grouping(self): @property @has_context def timing_information(self): - return getattr(flask.g, "timing_information", {}) + request = backends.backend.request_adapter() + return getattr(request.context, "timing_information", {}) @has_context def set_props(self, component_id: typing.Union[str, dict], props: dict): @@ -290,6 +291,14 @@ def path(self): """ return _get_from_context("path", "") + @property + @has_context + def args(self): + """ + Query parameters of the callback request as a dictionary-like object. + """ + return _get_from_context("args", "") + @property @has_context def remote(self): diff --git a/dash/_configs.py b/dash/_configs.py index edbf7b50d1..107b8308f5 100644 --- a/dash/_configs.py +++ b/dash/_configs.py @@ -1,5 +1,6 @@ import os -import flask + +from ._utils import get_root_path # noinspection PyCompatibility from . import exceptions @@ -127,7 +128,7 @@ def pages_folder_config(name, pages_folder, use_pages): if not pages_folder: return None is_custom_folder = str(pages_folder) != "pages" - pages_folder_path = os.path.join(flask.helpers.get_root_path(name), pages_folder) + pages_folder_path = os.path.join(get_root_path(name), pages_folder) if (use_pages or is_custom_folder) and not os.path.isdir(pages_folder_path): error_msg = f""" A folder called `{pages_folder}` does not exist. If a folder for pages is not diff --git a/dash/_hooks.py b/dash/_hooks.py index 3fe3c40e6d..1631b40ddc 100644 --- a/dash/_hooks.py +++ b/dash/_hooks.py @@ -3,7 +3,6 @@ from importlib import metadata as _importlib_metadata import typing_extensions as _tx -import flask as _f from .exceptions import HookError from .resources import ResourceType @@ -127,7 +126,7 @@ def route( Add a route to the Dash server. """ - def wrap(func: _t.Callable[[], _f.Response]): + def wrap(func: _t.Callable[[], _t.Any]): _name = name or func.__name__ self.add_hook( "routes", diff --git a/dash/_pages.py b/dash/_pages.py index 45538546e8..be9d847309 100644 --- a/dash/_pages.py +++ b/dash/_pages.py @@ -9,13 +9,11 @@ from pathlib import Path from urllib.parse import parse_qs -import flask - from . import _validate from ._callback_context import context_value from ._get_app import get_app from ._get_paths import get_relative_path -from ._utils import AttributeDict +from ._utils import AttributeDict, get_root_path CONFIG = AttributeDict() PAGE_REGISTRY = collections.OrderedDict() @@ -98,7 +96,7 @@ def _path_to_module_name(path): def _infer_module_name(page_path): relative_path = page_path.split(CONFIG.pages_folder)[-1] module = _path_to_module_name(relative_path) - proj_root = flask.helpers.get_root_path(CONFIG.name) + proj_root = get_root_path(CONFIG.name) if CONFIG.pages_folder.startswith(proj_root): parent_path = CONFIG.pages_folder[len(proj_root) :] else: @@ -150,23 +148,12 @@ def _parse_path_variables(pathname, path_template): return dict(zip(var_names, variables)) -def _create_redirect_function(redirect_to): - def redirect(): - return flask.redirect(redirect_to, code=301) - - return redirect - - 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.server.add_url_rule( - fullname, - fullname, - _create_redirect_function(app.get_relative_path(path)), - ) + app.backend.add_redirect_rule(app, fullname, app.get_relative_path(path)) def register_page( @@ -318,18 +305,22 @@ def register_page( ) page.update( supplied_title=title, - title=title - if title is not None - else CONFIG.title - if CONFIG.title != "Dash" - else page["name"], + title=( + title + if title is not None + else CONFIG.title + if CONFIG.title != "Dash" + else page["name"] + ), ) page.update( - description=description - if description - else CONFIG.description - if CONFIG.description - else "", + description=( + description + if description + else CONFIG.description + if CONFIG.description + else "" + ), order=order, supplied_order=order, supplied_layout=layout, @@ -389,16 +380,14 @@ def _path_to_page(path_id): return {}, None -def _page_meta_tags(app): - start_page, path_variables = _path_to_page(flask.request.path.strip("/")) +def _page_meta_tags(app, request): + request_path = request.path + start_page, path_variables = _path_to_page(request_path.strip("/")) - # use the supplied image_url or create url based on image in the assets folder image = start_page.get("image", "") if image: image = app.get_asset_url(image) - assets_image_url = ( - "".join([flask.request.url_root, image.lstrip("/")]) if image else None - ) + assets_image_url = "".join([request.root, image.lstrip("/")]) if image else None supplied_image_url = start_page.get("image_url") image_url = supplied_image_url if supplied_image_url else assets_image_url @@ -413,7 +402,7 @@ def _page_meta_tags(app): return [ {"name": "description", "content": description}, {"property": "twitter:card", "content": "summary_large_image"}, - {"property": "twitter:url", "content": flask.request.url}, + {"property": "twitter:url", "content": request.url}, {"property": "twitter:title", "content": title}, {"property": "twitter:description", "content": description}, {"property": "twitter:image", "content": image_url or ""}, diff --git a/dash/_utils.py b/dash/_utils.py index 48a378e1cf..5e241fe21d 100644 --- a/dash/_utils.py +++ b/dash/_utils.py @@ -3,6 +3,7 @@ import sys import uuid import hashlib +import importlib from collections import abc import subprocess import logging @@ -12,6 +13,7 @@ import string import inspect import re +import os from html import escape from functools import wraps @@ -104,6 +106,11 @@ def set_read_only(self, names, msg="Attribute is read-only"): else: object.__setattr__(self, "_read_only", new_read_only) + def unset_read_only(self, keys): + if hasattr(self, "_read_only"): + for key in keys: + self._read_only.pop(key, None) + def finalize(self, msg="Object is final: No new keys may be added."): """Prevent any new keys being set.""" object.__setattr__(self, "_final", msg) @@ -317,3 +324,60 @@ def pascal_case(name: Union[str, None]): return s[0].upper() + re.sub( r"[\-_\.]+([a-z])", lambda match: match.group(1).upper(), s[1:] ) + + +def get_root_path(import_name: str) -> str: + """Find the root path of a package, or the path that contains a + module. If it cannot be found, returns the current working + directory. + + Not to be confused with the value returned by :func:`find_package`. + + :meta private: + """ + # Module already imported and has a file attribute. Use that first. + mod = sys.modules.get(import_name) + + if mod is not None and hasattr(mod, "__file__") and mod.__file__ is not None: + return os.path.dirname(os.path.abspath(mod.__file__)) + + # Next attempt: check the loader. + try: + spec = importlib.util.find_spec(import_name) + + if spec is None: + raise ValueError + except (ImportError, ValueError): + loader = None + else: + loader = spec.loader + + # Loader does not exist or we're referring to an unloaded main + # module or a main module without path (interactive sessions), go + # with the current working directory. + if loader is None: + return os.getcwd() + + if hasattr(loader, "get_filename"): + filepath = loader.get_filename(import_name) # pyright: ignore + else: + # Fall back to imports. + __import__(import_name) + mod = sys.modules[import_name] + filepath = getattr(mod, "__file__", None) + + # If we don't have a file path it might be because it is a + # namespace package. In this case pick the root path from the + # first module that is contained in the package. + if filepath is None: + raise RuntimeError( + "No root path can be found for the provided module" + f" {import_name!r}. This can happen because the module" + " came from an import hook that does not provide file" + " name information or because it's a namespace package." + " In this case the root path needs to be explicitly" + " provided." + ) + + # filepath is import_name.py for a module, or __init__.py for a package. + return os.path.dirname(os.path.abspath(filepath)) # type: ignore[no-any-return] diff --git a/dash/_validate.py b/dash/_validate.py index f7502f245b..bb76f896e1 100644 --- a/dash/_validate.py +++ b/dash/_validate.py @@ -3,11 +3,11 @@ import re from textwrap import dedent from keyword import iskeyword -import flask from ._grouping import grouping_len, map_grouping from ._no_update import NoUpdate from .development.base_component import Component +from . import backends from . import exceptions from ._utils import ( patch_collections_abc, @@ -510,7 +510,7 @@ def validate_use_pages(config): "`dash.register_page()` must be called after app instantiation" ) - if flask.has_request_context(): + if backends.backend.has_request_context(): raise exceptions.PageError( """ dash.register_page() can’t be called within a callback as it updates dash.page_registry, which is a global variable. @@ -585,3 +585,42 @@ def _valid(out): return _valid(output) + + +def check_async(use_async): + if use_async is None: + try: + import asgiref # type: ignore[import-not-found] # pylint: disable=unused-import, import-outside-toplevel # noqa + + use_async = True + except ImportError: + pass + elif use_async: + try: + import asgiref # type: ignore[import-not-found] # pylint: disable=unused-import, import-outside-toplevel # noqa + except ImportError as exc: + raise Exception( + "You are trying to use dash[async] without having installed the requirements please install via: `pip install dash[async]`" + ) from exc + return use_async or False + + +def check_backend(backend, inferred_backend): + if backend is not None: + if isinstance(backend, type): + # get_backend returns the backend class for a string + # So we compare the class names + expected_backend_cls, _ = backends.get_backend(inferred_backend) + if ( + backend.__module__ != expected_backend_cls.__module__ + or backend.__name__ != expected_backend_cls.__name__ + ): + raise ValueError( + f"Conflict between provided backend '{backend.__name__}' and server type '{inferred_backend}'." + ) + elif not isinstance(backend, str): + raise ValueError("Invalid backend argument") + elif backend.lower() != inferred_backend: + raise ValueError( + f"Conflict between provided backend '{backend}' and server type '{inferred_backend}'." + ) diff --git a/dash/backends/__init__.py b/dash/backends/__init__.py new file mode 100644 index 0000000000..3a12e7939a --- /dev/null +++ b/dash/backends/__init__.py @@ -0,0 +1,79 @@ +import importlib +from typing import Type + +from .base_server import BaseDashServer + + +backend: BaseDashServer + + +_backend_imports = { + "flask": ("dash.backends._flask", "FlaskDashServer"), + "fastapi": ("dash.backends._fastapi", "FastAPIDashServer"), + "quart": ("dash.backends._quart", "QuartDashServer"), +} + + +def get_backend(name: str) -> Type[BaseDashServer]: + module_name, server_class = _backend_imports[name.lower()] + try: + module = importlib.import_module(module_name) + server = getattr(module, server_class) + return server + except KeyError as e: + raise ValueError(f"Unknown backend: {name}") from e + except ImportError as e: + raise ImportError( + f"Could not import module '{module_name}' for backend '{name}': {e}" + ) from e + except AttributeError as e: + raise AttributeError( + f"Module '{module_name}' does not have class '{server_class}' for backend '{name}': {e}" + ) from e + + +def _is_flask_instance(obj): + try: + # pylint: disable=import-outside-toplevel + from flask import Flask + + return isinstance(obj, Flask) + except ImportError: + return False + + +def _is_fastapi_instance(obj): + try: + # pylint: disable=import-outside-toplevel + from fastapi import FastAPI # type: ignore[import-not-found] + + return isinstance(obj, FastAPI) + except ImportError: + return False + + +def _is_quart_instance(obj): + try: + # pylint: disable=import-outside-toplevel + from quart import Quart # type: ignore[import-not-found] + + return isinstance(obj, Quart) + except ImportError: + return False + + +def get_server_type(server): + if _is_flask_instance(server): + return "flask" + if _is_quart_instance(server): + return "quart" + if _is_fastapi_instance(server): + return "fastapi" + raise ValueError("Invalid backend argument") + + +__all__ = [ + "get_backend", + "backend", + "get_server_type", +] diff --git a/dash/backends/_fastapi.py b/dash/backends/_fastapi.py new file mode 100644 index 0000000000..0b27f43692 --- /dev/null +++ b/dash/backends/_fastapi.py @@ -0,0 +1,645 @@ +from __future__ import annotations + +import asyncio +from contextvars import copy_context, ContextVar +import json +from typing import TYPE_CHECKING, Any, Callable, Dict +import sys +import mimetypes +import hashlib +import inspect +import pkgutil +import time +import os +import subprocess +import threading + +try: + from fastapi import FastAPI, Request, Response, Body + from fastapi.responses import JSONResponse, RedirectResponse + from fastapi.staticfiles import StaticFiles + from starlette.responses import Response as StarletteResponse + from starlette.datastructures import MutableHeaders + from starlette.types import ASGIApp, Scope, Receive, Send + import uvicorn +except ImportError as _err: + raise ImportError( + "All dependencies not installed. Please install it with `dash[fastapi]` to use the FastAPI backend." + ) from _err + +from dash.fingerprint import check_fingerprint +from dash import _validate +from dash.exceptions import PreventUpdate +from .base_server import BaseDashServer, RequestAdapter, ResponseAdapter +from ._utils import format_traceback_html + +if TYPE_CHECKING: # pragma: no cover - typing only + from dash import Dash + + +class FastAPIResponseAdapter(ResponseAdapter): + """ + A custom Response class that wraps FastAPI's JSONResponse + and provides a set_response() method for compatibility with Dash's callback system. + """ + + @property + def callback_response(self): + """Get the response object to be returned from a callback.""" + print( + "Cannot access callback_response directly on FastAPIResponseAdapter. Use set_response() to create a response with data." + ) + raise NotImplementedError() + + def set_response(self, **kwargs): + """ + Set the response data. This method provides compatibility with Flask's Response.set_data(). + """ + data = kwargs.get("data") + if isinstance(data, (str, bytes, bytearray)): + resp = Response(content=data) + else: + resp = JSONResponse(content=data) + if self._headers: + for key, value in self._headers.items(): + if isinstance(value, list): + for v in value: + resp.headers.append(key, v) + else: + resp.headers[key] = value + if self._cookies: + for key, (value, cookie_kwargs) in self._cookies.items(): + resp.set_cookie(key, value, **cookie_kwargs) + return resp + + +_current_request_var = ContextVar("dash_current_request", default=None) + + +def set_current_request(req): + return _current_request_var.set(req) + + +def reset_current_request(token): + _current_request_var.reset(token) + + +def get_current_request() -> Request: + req = _current_request_var.get() + if req is None: + raise RuntimeError("No active request in context") + return req + + +_ENV_CONFIG = "_DASH_FASTAPI_CONFIG" + + +class DashMiddleware: # pylint: disable=too-few-public-methods + """Consolidated middleware for all Dash/FastAPI integration needs.""" + + def __init__( + self, + app: ASGIApp, + dash_app: Dash, + dash_server: FastAPIDashServer, + before_request_funcs: list, + after_request_func: Callable | None = None, + enable_timing: bool = False, + ) -> None: + self.app = app + self.dash_app = dash_app + self.dash_server = dash_server + self.before_request_funcs = before_request_funcs + self.after_request_func = after_request_func + self.enable_timing = enable_timing + self._dev_tools_initialized = False + + async def _initialize_dev_tools(self) -> None: + """Initialize dev tools from environment config on first run.""" + if not self._dev_tools_initialized: + config = json.loads(os.getenv(_ENV_CONFIG, "{}")) + if config: + self.dash_app.enable_dev_tools(**config, first_run=False) + self._dev_tools_initialized = True + + def _setup_timing(self, request: Request) -> None: + """Set up timing information for the request.""" + if self.enable_timing: + request.state.timing_information = { + "__dash_server": {"dur": time.time(), "desc": None} + } + + async def _run_before_hooks(self) -> None: + """Run all before-request hooks.""" + for func in self.before_request_funcs: + if inspect.iscoroutinefunction(func): + await func() + else: + func() + + async def _run_after_hooks(self) -> None: + """Run after-request hook if configured.""" + if self.after_request_func is not None: + if inspect.iscoroutinefunction(self.after_request_func): + await self.after_request_func() + else: + self.after_request_func() + + def _finalize_timing(self, request: Request) -> dict | None: + """Calculate final timing information and return headers to add.""" + if not self.enable_timing or not hasattr(request.state, "timing_information"): + return None + + timing_information = request.state.timing_information + dash_total = timing_information.get("__dash_server", None) + if dash_total is not None: + dash_total["dur"] = round((time.time() - dash_total["dur"]) * 1000) + + return timing_information + + async def _handle_error( + self, error: Exception, scope: Scope, receive: Receive, send: Send + ) -> None: + """Handle exceptions during request processing.""" + if isinstance(error, PreventUpdate): + response = Response(status_code=204) + elif self.dash_server.error_handling_mode in ["raise", "prune"]: + tb = self.dash_server._get_traceback(None, error) # pylint: disable=W0212 + response = Response(content=tb, media_type="text/html", status_code=500) + else: + response = JSONResponse( + status_code=500, + content={ + "error": "InternalServerError", + "message": "An internal server error occurred.", + }, + ) + await response(scope, receive, send) + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + # Handle lifespan events (startup/shutdown) + if scope["type"] == "lifespan": + await self._initialize_dev_tools() + await self.app(scope, receive, send) + return + + # Non-HTTP/WebSocket scopes pass through + if scope["type"] not in ("http", "websocket"): + await self.app(scope, receive, send) + return + + # HTTP/WebSocket request handling + request = Request(scope, receive=receive) + token = set_current_request(request) + + try: + self._setup_timing(request) + await self._run_before_hooks() + + await self.app(scope, receive, send) + + await self._run_after_hooks() + self._finalize_timing(request) + + except Exception as e: # pylint: disable=W0718 + await self._handle_error(e, scope, receive, send) + finally: + reset_current_request(token) + + +class FastAPIDashServer(BaseDashServer[FastAPI]): + def __init__(self, server: FastAPI): + super().__init__(server) + self.server_type = "fastapi" + self.error_handling_mode = "ignore" + self.request_adapter = FastAPIRequestAdapter + self.response_adapter = FastAPIResponseAdapter + self._before_request_funcs = [] + self._after_request_func = None + self._enable_timing = False + + def __call__(self, *args: Any, **kwargs: Any): + # ASGI: pass through to FastAPI + return self.server(*args, **kwargs) + + @staticmethod + # pylint: disable=W0613 + def create_app(name: str = "__main__", config: Dict[str, Any] | None = None): + app = FastAPI() + + if config: + for key, value in config.items(): + setattr(app.state, key, value) + return app + + def register_assets_blueprint( + self, blueprint_name: str, assets_url_path: str, assets_folder: str + ): + try: + self.server.mount( + assets_url_path, + StaticFiles(directory=assets_folder), + name=blueprint_name, + ) + except RuntimeError: + # directory doesnt exist + pass + + def register_error_handlers(self): + self.error_handling_mode = "ignore" + + def _get_traceback(self, _secret, error: Exception): + return format_traceback_html( + error, self.error_handling_mode, "FastAPI Debugger", "FastAPI" + ) + + def register_prune_error_handler(self, _secret, prune_errors): + if prune_errors: + self.error_handling_mode = "prune" + else: + self.error_handling_mode = "raise" + + def _html_response_wrapper(self, view_func: Callable[..., Any] | str): + async def wrapped(*_args, **_kwargs): + # If view_func is a function, call it; if it's a string, use it directly + html = view_func() if callable(view_func) else view_func + return Response(content=html, media_type="text/html") + + return wrapped + + def setup_index(self, dash_app: Dash): + async def index(_request: Request): + return Response(content=dash_app.index(), media_type="text/html") + + # pylint: disable=protected-access + dash_app._add_url("", index, methods=["GET"]) + + def setup_catchall(self, dash_app: Dash): + async def catchall(_request: Request): + return Response(content=dash_app.index(), media_type="text/html") + + # pylint: disable=protected-access + dash_app._add_url("{path:path}", catchall, methods=["GET"]) + + def add_url_rule( + self, + rule: str, + view_func: Callable[..., Any] | str, + endpoint: str | None = None, + methods: list[str] | None = None, + include_in_schema: bool = False, + ): + if rule == "": + rule = "/" + if isinstance(view_func, str): + # Wrap string or sync function to async FastAPI handler + view_func = self._html_response_wrapper(view_func) + self.server.add_api_route( + rule, + view_func, + methods=methods or ["GET"], + name=endpoint, + include_in_schema=include_in_schema, + ) + + def before_request(self, func: Callable[[], Any] | None): + if func is not None: + self._before_request_funcs.append(func) + + def after_request(self, func: Callable[[], Any] | None): + self._after_request_func = func + + def has_request_context(self) -> bool: + try: + get_current_request() + return True + except RuntimeError: + return False + + def run(self, dash_app: Dash, host, port, debug, **kwargs): # pylint: disable=R0912 + frame = inspect.stack()[2] + if debug and kwargs.get("reload") is None: + kwargs["reload"] = True + + # Check if we're running in a thread (e.g., from testing framework) + # If so, run uvicorn directly instead of spawning a subprocess + is_threaded = threading.current_thread() != threading.main_thread() + + if is_threaded: + # Running in a thread (testing context) - use uvicorn.run directly + # This allows the testing framework to control the server lifecycle + if kwargs.get("reload"): + kwargs["reload"] = True + uvicorn.run(self.server, host=host, port=port, **kwargs) + else: + # Running in main thread (normal context) - use subprocess + file_path = frame.filename + rel_path = os.path.relpath(file_path, os.getcwd()) + + # Check if the file is outside the current working directory + if rel_path.startswith(".."): + # File is outside cwd, try to find the module name from sys.modules + module_name = None + for mod_name, mod in sys.modules.items(): + if hasattr(mod, "__file__") and mod.__file__: + if os.path.abspath(mod.__file__) == os.path.abspath(file_path): + module_name = mod_name + break + + # If we still can't find it, raise an error + if not module_name: + raise RuntimeError( + f"Cannot determine module name for {file_path}. " + "The file is outside the current working directory and not found in sys.modules. " + "Please ensure the FastAPI app is being run from a file within the current working directory." + ) + else: + # File is within cwd, use relative path + module_name = os.path.splitext(rel_path)[0].replace(os.sep, ".") + + # Find the Dash app variable name by inspecting the calling frame + dash_var_name = None + calling_frame = frame.frame + for var_name, var_value in calling_frame.f_locals.items(): + if var_value is dash_app: + dash_var_name = var_name + break + + # If not found in locals, check globals + if not dash_var_name: + for var_name, var_value in calling_frame.f_globals.items(): + if var_value is dash_app: + dash_var_name = var_name + break + + # Construct the app path - use .server to access the FastAPI instance + if dash_var_name: + app_path = f"{module_name}:{dash_var_name}.server" + else: + # Fallback to looking for 'server' variable (old behavior) + app_path = f"{module_name}:server" + + uvicorn_args = [ + sys.executable, + "-m", + "uvicorn", + app_path, + "--host", + str(host), + "--port", + str(port), + ] + if kwargs.get("reload"): + uvicorn_args.append("--reload") + + dev_tools = dash_app._dev_tools # pylint: disable=W0212 + config = dict( + {"debug": debug} if debug else {"debug": False}, + **{f"dev_tools_{k}": v for k, v in dev_tools.items()}, + ) + env = os.environ.copy() + env[_ENV_CONFIG] = json.dumps(config) + + # Add any other kwargs as CLI args if needed + + # pylint: disable=R1732 + proc = subprocess.Popen(uvicorn_args, env=env) + proc.wait() + + def make_response( + self, + data: str | bytes | bytearray, + mimetype: str | None = None, + content_type: str | None = None, + status: int | None = None, + ): + headers = {} + if mimetype: + headers["content-type"] = mimetype + if content_type: + headers["content-type"] = content_type + return Response(content=data, headers=headers, status_code=status or 200) + + def jsonify(self, obj: Any): + return JSONResponse(content=obj) + + def serve_component_suites( + self, + dash_app: Dash, + package_name: str, + fingerprinted_path: str, + request: Request, + ): + + path_in_pkg, has_fingerprint = check_fingerprint(fingerprinted_path) + _validate.validate_js_path(dash_app.registered_paths, package_name, path_in_pkg) + extension = "." + path_in_pkg.split(".")[-1] + mimetype = mimetypes.types_map.get(extension, "application/octet-stream") + package = sys.modules[package_name] + dash_app.logger.debug( + "serving -- package: %s[%s] resource: %s => location: %s", + package_name, + package.__version__, + path_in_pkg, + package.__path__, + ) + data = pkgutil.get_data(package_name, path_in_pkg) + headers = {} + if has_fingerprint: + headers["Cache-Control"] = "public, max-age=31536000" + return StarletteResponse(content=data, media_type=mimetype, headers=headers) + etag = hashlib.md5(data).hexdigest() if data else "" + headers["ETag"] = etag + if request.headers.get("if-none-match") == etag: + return StarletteResponse(status_code=304) + return StarletteResponse(content=data, media_type=mimetype, headers=headers) + + def setup_component_suites(self, dash_app: Dash): + async def serve(request: Request, package_name: str, fingerprinted_path: str): + return self.serve_component_suites( + dash_app, package_name, fingerprinted_path, request + ) + + name = "_dash-component-suites/{package_name}/{fingerprinted_path:path}" + dash_app._add_url(name, serve) # pylint: disable=protected-access + + def _create_redirect_function(self, redirect_to): + def _redirect(): + return RedirectResponse(url=redirect_to, status_code=301) + + return _redirect + + def add_redirect_rule(self, app, fullname, path): + self.server.add_api_route( + fullname, + self._create_redirect_function(app.get_relative_path(path)), + methods=["GET"], + name=fullname, + include_in_schema=False, + ) + + def serve_callback(self, dash_app: Dash): + async def _dispatch(request: Request): + # pylint: disable=protected-access + body = await request.json() + cb_ctx = dash_app._initialize_context( + body + ) # pylint: disable=protected-access + func = dash_app._prepare_callback( + cb_ctx, body + ) # pylint: disable=protected-access + args = dash_app._inputs_to_vals( + cb_ctx.inputs_list + cb_ctx.states_list + ) # pylint: disable=protected-access + ctx = copy_context() + partial_func = dash_app._execute_callback( + func, args, cb_ctx.outputs_list, cb_ctx + ) # pylint: disable=protected-access + response_data = ctx.run(partial_func) + if inspect.iscoroutine(response_data): + response_data = await response_data + return cb_ctx.dash_response.set_response(data=response_data) + + return _dispatch + + def register_timing_hooks(self, first_run: bool): + if first_run: + self._enable_timing = True + + def register_callback_api_routes( + self, callback_api_paths: Dict[str, Callable[..., Any]] + ): + """ + Register callback API endpoints on the FastAPI app. + Each key in callback_api_paths is a route, each value is a handler (sync or async). + Accepts a JSON body (dict) and filters keys based on the handler's signature. + """ + for path, handler in callback_api_paths.items(): + endpoint = f"dash_callback_api_{path}" + route = path if path.startswith("/") else f"/{path}" + methods = ["POST"] + sig = inspect.signature(handler) + param_names = list(sig.parameters.keys()) + + def make_view_func(handler, param_names): + async def view_func(_request: Request, body: dict = Body(...)): + kwargs = { + k: v + for k, v in body.items() + if k in param_names and v is not None + } + if inspect.iscoroutinefunction(handler): + result = await handler(**kwargs) + else: + result = handler(**kwargs) + return JSONResponse(content=result) + + return view_func + + self.server.add_api_route( + route, + make_view_func(handler, param_names), + methods=methods, + name=endpoint, + include_in_schema=True, + ) + + def enable_compression(self) -> None: + # pylint: disable=import-outside-toplevel,import-error + from fastapi.middleware.gzip import ( + GZipMiddleware, + ) + + self.server.add_middleware(GZipMiddleware, minimum_size=500) + + def setup_backend(self, dash_app: Dash): + # Add consolidated middleware for all Dash functionality + self.server.add_middleware( + DashMiddleware, + dash_app=dash_app, + dash_server=self, + before_request_funcs=self._before_request_funcs, + after_request_func=self._after_request_func, + enable_timing=self._enable_timing, + ) + + # Add timing middleware separately if enabled (needs to modify response headers) + if self._enable_timing: + + @self.server.middleware("http") + async def timing_headers_middleware(request: Request, call_next): + response = await call_next(request) + timing_information = getattr(request.state, "timing_information", None) + if timing_information is not None: + headers = MutableHeaders(response.headers) + for name, info in timing_information.items(): + value = name + if info.get("desc") is not None: + value += f';desc="{info["desc"]}"' + if info.get("dur") is not None: + value += f";dur={info['dur']}" + headers.append("Server-Timing", value) + return response + + +class FastAPIRequestAdapter(RequestAdapter): + def __init__(self): + self._request: Request = get_current_request() + super().__init__() + + def __call__(self): + self._request = get_current_request() + return self + + @property + def context(self): + if self._request is None: + raise RuntimeError("No active request in context") + + return self._request.state + + @property + def root(self): + return str(self._request.base_url) + + @property + def args(self): + return self._request.query_params + + @property + def is_json(self): + return self._request.headers.get("content-type", "").startswith( + "application/json" + ) + + @property + def cookies(self): + return self._request.cookies + + @property + def headers(self): + return self._request.headers + + @property + def full_path(self): + return str(self._request.url) + + @property + def url(self): + return str(self._request.url) + + @property + def remote_addr(self): + client = getattr(self._request, "client", None) + return getattr(client, "host", None) + + @property + def origin(self): + return self._request.headers.get("origin") + + @property + def path(self): + return self._request.url.path + + def get_json(self): + return asyncio.run(self._request.json()) diff --git a/dash/backends/_flask.py b/dash/backends/_flask.py new file mode 100644 index 0000000000..00c8730d8a --- /dev/null +++ b/dash/backends/_flask.py @@ -0,0 +1,432 @@ +from __future__ import annotations + +import asyncio +import pkgutil +import sys +import mimetypes +import time +import inspect +import traceback + +from contextvars import copy_context +from typing import TYPE_CHECKING, Any, Callable, Dict + +from importlib_metadata import version as _get_distribution_version + +from flask import ( + Flask, + Blueprint, + Response, + request, + jsonify, + g as flask_g, + has_request_context, + redirect, +) +from werkzeug.debug import tbtools + +from dash.fingerprint import check_fingerprint +from dash import _validate +from dash.exceptions import PreventUpdate, InvalidResourceError +from dash._callback import _invoke_callback, _async_invoke_callback +from dash._utils import parse_version +from .base_server import BaseDashServer, RequestAdapter, ResponseAdapter + + +if TYPE_CHECKING: # pragma: no cover - typing only + from dash import Dash + + +class FlaskResponseAdapter(ResponseAdapter): + """ + A custom Response class that wraps Flask's Response + and provides a set_response() method for compatibility with Dash's callback system. + """ + + def __init__(self): + self._flask_response = Response(content_type="application/json") + super().__init__() + + @property + def callback_response(self) -> Response: + return self._flask_response + + def set_cookie(self, key, value="", **kwargs): + self._flask_response.set_cookie(key, value, **kwargs) + + def append_header(self, key, value): + self._flask_response.headers.add(key, value) + + def set_header(self, key, value): + self._flask_response.headers.set(key, value) + + def set_response(self, **kwargs): + self._flask_response.set_data(kwargs.get("data", "")) + return self._flask_response + + +class FlaskDashServer(BaseDashServer[Flask]): + def __init__(self, server: Flask) -> None: + super().__init__(server) + self.server_type = "flask" + self.request_adapter = FlaskRequestAdapter + self.response_adapter = FlaskResponseAdapter + + def __call__(self, *args: Any, **kwargs: Any): + # Always WSGI + return self.server(*args, **kwargs) + + @staticmethod + def create_app(name: str = "__main__", config: Dict[str, Any] | None = None): + app = Flask(name) + if config: + app.config.update(config) + return app + + def register_assets_blueprint( + self, blueprint_name: str, assets_url_path: str, assets_folder: str + ): + bp = Blueprint( + blueprint_name, + __name__, + static_folder=assets_folder, + static_url_path=assets_url_path, + ) + self.server.register_blueprint(bp) + + def register_error_handlers(self): + @self.server.errorhandler(PreventUpdate) + def _handle_error(_): + return "", 204 + + @self.server.errorhandler(InvalidResourceError) + def _invalid_resources_handler(err): + return err.args[0], 404 + + def _get_traceback(self, secret, error: Exception): + def _get_skip(error): + tb = error.__traceback__ + skip = 1 + while tb.tb_next is not None: + skip += 1 + tb = tb.tb_next + if tb.tb_frame.f_code in [ + _invoke_callback.__code__, + _async_invoke_callback.__code__, + ]: + return skip + return skip + + def _do_skip(error): + tb = error.__traceback__ + while tb.tb_next is not None: + if tb.tb_frame.f_code in [ + _invoke_callback.__code__, + _async_invoke_callback.__code__, + ]: + return tb.tb_next + tb = tb.tb_next + return error.__traceback__ + + if hasattr(tbtools, "get_current_traceback"): + return tbtools.get_current_traceback(skip=_get_skip(error)).render_full() + if hasattr(tbtools, "DebugTraceback"): + return tbtools.DebugTraceback( + error, skip=_get_skip(error) + ).render_debugger_html(True, secret, True) + return "".join(traceback.format_exception(type(error), error, _do_skip(error))) + + def register_prune_error_handler(self, secret, prune_errors): + if prune_errors: + + @self.server.errorhandler(Exception) + def _wrap_errors(error): + tb = self._get_traceback(secret, error) + return tb, 500 + + def add_url_rule( + self, + rule: str, + view_func: Callable[..., Any], + endpoint: str | None = None, + methods: list[str] | None = None, + ): + self.server.add_url_rule( + rule, view_func=view_func, endpoint=endpoint, methods=methods or ["GET"] + ) + + def before_request(self, func: Callable[[], Any]): + # Flask expects a callable; user responsibility not to pass None + self.server.before_request(func) + + def after_request(self, func: Callable[[Any], Any]): + # Flask after_request expects a function(response) -> response + self.server.after_request(func) + + def has_request_context(self) -> bool: + return has_request_context() + + def run(self, dash_app: Dash, host: str, port: int, debug: bool, **kwargs: Any): + self.server.run(host=host, port=port, debug=debug, **kwargs) + + def make_response( + self, + data: str | bytes | bytearray, + mimetype: str | None = None, + content_type: str | None = None, + status: int | None = None, + ): + return Response( + data, mimetype=mimetype, content_type=content_type, status=status + ) + + def jsonify(self, obj: Any): + return jsonify(obj) + + def setup_catchall(self, dash_app: Dash): + def catchall(*args, **kwargs): + return dash_app.index(*args, **kwargs) + + # pylint: disable=protected-access + dash_app._add_url("", catchall, methods=["GET"]) + + def setup_index(self, dash_app: Dash): + def index(*args, **kwargs): + return dash_app.index(*args, **kwargs) + + # pylint: disable=protected-access + dash_app._add_url("", index, methods=["GET"]) + + def serve_component_suites( + self, dash_app: Dash, package_name: str, fingerprinted_path: str + ): + path_in_pkg, has_fingerprint = check_fingerprint(fingerprinted_path) + _validate.validate_js_path(dash_app.registered_paths, package_name, path_in_pkg) + extension = "." + path_in_pkg.split(".")[-1] + mimetype = mimetypes.types_map.get(extension, "application/octet-stream") + package = sys.modules[package_name] + dash_app.logger.debug( + "serving -- package: %s[%s] resource: %s => location: %s", + package_name, + package.__version__, + path_in_pkg, + package.__path__, + ) + data = pkgutil.get_data(package_name, path_in_pkg) + response = Response(data, mimetype=mimetype) + if has_fingerprint: + response.cache_control.max_age = 31536000 # 1 year + else: + response.add_etag() + tag = response.get_etag()[0] + request_etag = request.headers.get("If-None-Match") + if f'"{tag}"' == request_etag: + response = Response(None, status=304) + return response + + def setup_component_suites(self, dash_app: Dash): + def serve(package_name, fingerprinted_path): + return self.serve_component_suites( + dash_app, package_name, fingerprinted_path + ) + + # pylint: disable=protected-access + dash_app._add_url( + "_dash-component-suites//", + serve, + ) + + def _create_redirect_function(self, redirect_to): + def _redirect(): + return redirect(redirect_to, code=301) + + return _redirect + + def add_redirect_rule(self, app, fullname, path): + self.server.add_url_rule( + fullname, + fullname, + self._create_redirect_function(app.get_relative_path(path)), + ) + + # pylint: disable=unused-argument + def serve_callback(self, dash_app: Dash): + def _dispatch(): + body = request.get_json() + # pylint: disable=protected-access + cb_ctx = dash_app._initialize_context(body) + func = dash_app._prepare_callback(cb_ctx, body) + args = dash_app._inputs_to_vals(cb_ctx.inputs_list + cb_ctx.states_list) + ctx = copy_context() + partial_func = dash_app._execute_callback( + func, args, cb_ctx.outputs_list, cb_ctx + ) + response_data = ctx.run(partial_func) + if asyncio.iscoroutine(response_data): + raise Exception( + "You are trying to use a coroutine without dash[async]. " + "Please install the dependencies via `pip install dash[async]` and ensure " + "that `use_async=False` is not being passed to the app." + ) + return cb_ctx.dash_response.set_response(data=response_data) + + async def _dispatch_async(): + body = request.get_json() + # pylint: disable=protected-access + cb_ctx = dash_app._initialize_context(body) + func = dash_app._prepare_callback(cb_ctx, body) + args = dash_app._inputs_to_vals(cb_ctx.inputs_list + cb_ctx.states_list) + ctx = copy_context() + partial_func = dash_app._execute_callback( + func, args, cb_ctx.outputs_list, cb_ctx + ) + response_data = ctx.run(partial_func) + if asyncio.iscoroutine(response_data): + response_data = await response_data + return cb_ctx.dash_response.set_response(data=response_data) + + if dash_app._use_async: # pylint: disable=protected-access + return _dispatch_async + return _dispatch + + def register_timing_hooks(self, _first_run: bool): + # Define timing hooks inside method scope and register them + def _before_request() -> None: + flask_g.timing_information = { # type: ignore[attr-defined] + "__dash_server": {"dur": time.time(), "desc": None} + } + + def _after_request(response: Response): # type: ignore[name-defined] + timing_information = flask_g.get("timing_information", None) # type: ignore[attr-defined] + if timing_information is None: + return response + dash_total = timing_information.get("__dash_server", None) + if dash_total is not None: + dash_total["dur"] = round((time.time() - dash_total["dur"]) * 1000) + for name, info in timing_information.items(): + value = name + if info.get("desc") is not None: + value += f';desc="{info["desc"]}"' + if info.get("dur") is not None: + value += f";dur={info['dur']}" + response.headers.add("Server-Timing", value) + return response + + self.before_request(_before_request) + self.after_request(_after_request) + + def register_callback_api_routes( + self, callback_api_paths: Dict[str, Callable[..., Any]] + ): + """ + Register callback API endpoints on the Flask app. + Each key in callback_api_paths is a route, each value is a handler (sync or async). + The view function parses the JSON body and passes it to the handler. + """ + for path, handler in callback_api_paths.items(): + endpoint = f"dash_callback_api_{path}" + route = path if path.startswith("/") else f"/{path}" + methods = ["POST"] + + if inspect.iscoroutinefunction(handler): + + async def _async_view_func(*args, handler=handler, **kwargs): + data = request.get_json() + result = await handler(**data) if data else await handler() + return jsonify(result) + + view_func = _async_view_func + else: + + def _sync_view_func(*args, handler=handler, **kwargs): + data = request.get_json() + result = handler(**data) if data else handler() + return jsonify(result) + + view_func = _sync_view_func + + view_func = _sync_view_func + + # Flask 2.x+ supports async views natively + self.server.add_url_rule( + route, endpoint=endpoint, view_func=view_func, methods=methods + ) + + def enable_compression(self) -> None: + try: + import flask_compress # pylint: disable=import-outside-toplevel + + Compress = flask_compress.Compress + Compress(self.server) + _flask_compress_version = parse_version( + _get_distribution_version("flask_compress") + ) + if not hasattr( + self.server.config, "COMPRESS_ALGORITHM" + ) and _flask_compress_version >= parse_version("1.6.0"): + self.server.config["COMPRESS_ALGORITHM"] = ["gzip"] + except ImportError as error: + raise ImportError( + "To use the compress option, you need to install dash[compress]" + ) from error + + +class FlaskRequestAdapter(RequestAdapter): + """Flask implementation using property-based accessors.""" + + def __init__(self) -> None: + # Store the request LocalProxy so we can reference it consistently + self._request = request + super().__init__() + + def __call__(self, *args: Any, **kwds: Any): + return self + + @property + def context(self): + if not has_request_context(): + raise RuntimeError("No active request in context") + return flask_g + + @property + def args(self): + return self._request.args + + @property + def root(self): + return self._request.url_root + + def get_json(self): # kept as method + return self._request.get_json() + + @property + def is_json(self): + return self._request.is_json + + @property + def cookies(self): + return self._request.cookies + + @property + def headers(self): + return self._request.headers + + @property + def url(self): + return self._request.url + + @property + def full_path(self): + return self._request.full_path + + @property + def remote_addr(self): + return self._request.remote_addr + + @property + def origin(self): + return getattr(self._request, "origin", None) + + @property + def path(self): + return self._request.path diff --git a/dash/backends/_quart.py b/dash/backends/_quart.py new file mode 100644 index 0000000000..ddf31ff2f4 --- /dev/null +++ b/dash/backends/_quart.py @@ -0,0 +1,447 @@ +from __future__ import annotations + +import typing as _t +import mimetypes +import inspect +import pkgutil +import time +import sys + +from logging.config import dictConfig +from contextvars import copy_context +from typing import Any + +from importlib_metadata import version as _get_distribution_version + +# Attempt top-level Quart imports; allow absence if user not using quart backend +try: + from quart import ( + Quart, + Response, + jsonify, + request, + Blueprint, + g as quart_g, + has_request_context, + redirect, + ) +except ImportError as _err: + raise ImportError( + "All dependencies not installed. Please install it with `dash[quart]` to use the Quart backend." + ) from _err + +from dash.exceptions import PreventUpdate, InvalidResourceError +from dash.fingerprint import check_fingerprint +from dash._utils import parse_version +from dash import _validate, Dash +from .base_server import BaseDashServer, RequestAdapter, ResponseAdapter +from ._utils import format_traceback_html + + +class QuartResponseAdapter(ResponseAdapter): + """ + A custom Response class that wraps Quart's Response + and provides a set_response() method for compatibility with Dash's callback system. + """ + + def __init__(self): + self._quart_response = Response(content_type="application/json") + super().__init__() + + @property + def callback_response(self) -> Response: + return self._quart_response + + def set_cookie(self, key, value="", **kwargs): + self._quart_response.set_cookie(key, value, **kwargs) + + def append_header(self, key, value): + self._quart_response.headers.add(key, value) + + def set_header(self, key, value): + self._quart_response.headers.set(key, value) + + def set_response(self, **kwargs): + self._quart_response.set_data(kwargs.get("data", "")) + return self._quart_response + + +class QuartDashServer(BaseDashServer[Quart]): + def __init__(self, server: Quart) -> None: + super().__init__(server) + self.server_type = "quart" + self.config = {} + self.error_handling_mode = "ignore" + self.request_adapter = QuartRequestAdapter + self.response_adapter = QuartResponseAdapter + + def __call__(self, *args: Any, **kwargs: Any): # type: ignore[name-defined] + return self.server(*args, **kwargs) + + @staticmethod + def create_app( + name: str = "__main__", config: _t.Optional[_t.Dict[str, _t.Any]] = None + ): + if Quart is None: + raise RuntimeError( + "Quart is not installed. Install with 'pip install quart' to use the quart backend." + ) + app = Quart(name) # type: ignore + if config: + for key, value in config.items(): + app.config[key] = value + return app + + def register_assets_blueprint( + self, blueprint_name: str, assets_url_path: str, assets_folder: str # type: ignore[name-defined] + ): + + bp = Blueprint( + blueprint_name, + __name__, + static_folder=assets_folder, + static_url_path=assets_url_path, + ) + self.server.register_blueprint(bp) + + def _get_traceback(self, _secret, error: Exception): + return format_traceback_html( + error, self.error_handling_mode, "Quart Debugger", "Quart" + ) + + def register_prune_error_handler(self, secret, prune_errors): + if prune_errors: + self.error_handling_mode = "prune" + else: + self.error_handling_mode = "raise" + + @self.server.errorhandler(Exception) + async def _wrap_errors(error): + if self.error_handling_mode == "ignore": + return Response( + "Internal server error.", status=500, content_type="text/plain" + ) + tb = self._get_traceback(secret, error) + return Response(tb, status=500, content_type="text/html") + + def register_timing_hooks(self, _first_run: bool): # type: ignore[name-defined] parity with Flask factory + @self.server.before_request + async def _before_request(): # pragma: no cover - timing infra + if quart_g is not None: + quart_g.timing_information = { # type: ignore[attr-defined] + "__dash_server": {"dur": time.time(), "desc": None} + } + + @self.server.after_request + async def _after_request(response): # pragma: no cover - timing infra + timing_information = ( + getattr(quart_g, "timing_information", None) + if quart_g is not None + else None + ) + if timing_information is None: + return response + dash_total = timing_information.get("__dash_server", None) + if dash_total is not None: + dash_total["dur"] = round((time.time() - dash_total["dur"]) * 1000) + for name, info in timing_information.items(): + value = name + if info.get("desc") is not None: + value += f';desc="{info["desc"]}"' + if info.get("dur") is not None: + value += f";dur={info['dur']}" + # Quart/Werkzeug headers expose 'add' (not 'append') + if hasattr(response.headers, "add"): + response.headers.add("Server-Timing", value) + else: # fallback just in case + response.headers["Server-Timing"] = value + return response + + def register_error_handlers(self): # type: ignore[name-defined] + @self.server.errorhandler(PreventUpdate) + async def _prevent_update(_): + return "", 204 + + @self.server.errorhandler(InvalidResourceError) + async def _invalid_resource(err): + return err.args[0], 404 + + def _html_response_wrapper(self, view_func: _t.Callable[..., _t.Any] | str): + async def wrapped(*_args, **_kwargs): + html_val = view_func() if callable(view_func) else view_func + if inspect.iscoroutine(html_val): # handle async function returning html + html_val = await html_val + html = str(html_val) + return Response(html, content_type="text/html") + + return wrapped + + def add_url_rule( + self, + rule: str, + view_func: _t.Callable[..., _t.Any], + endpoint: str | None = None, + methods: list[str] | None = None, + ): + self.server.add_url_rule( + rule, view_func=view_func, endpoint=endpoint, methods=methods or ["GET"] + ) + + def setup_index(self, dash_app: Dash): # type: ignore[name-defined] + async def index(*args, **kwargs): + return Response(dash_app.index(*args, **kwargs), content_type="text/html") # type: ignore[arg-type] + + # pylint: disable=protected-access + dash_app._add_url("", index, methods=["GET"]) + + def setup_catchall(self, dash_app: Dash): + async def catchall( + path: str, *args, **kwargs + ): # noqa: ARG001 - path is unused but kept for route signature, pylint: disable=unused-argument + return Response(dash_app.index(*args, **kwargs), content_type="text/html") # type: ignore[arg-type] + + # pylint: disable=protected-access + dash_app._add_url("", catchall, methods=["GET"]) + + def before_request(self, func: _t.Callable[[], _t.Any]): + self.server.before_request(func) + + def after_request(self, func: _t.Callable[[], _t.Any]): + @self.server.after_request + async def _after(response): + if func is not None: + result = func() + if inspect.iscoroutine(result): # Allow async hooks + await result + return response + + def has_request_context(self) -> bool: + if has_request_context is None: + raise RuntimeError("Quart not installed; cannot check request context") + return has_request_context() + + # pylint: disable=W0613 + def run(self, dash_app: Dash, host: str, port: int, debug: bool, **kwargs: _t.Any): + self.config = {"debug": debug, **kwargs} if debug else kwargs + # pylint: disable=protected-access + if dash_app._dev_tools.silence_routes_logging: + dictConfig( + { + "version": 1, + "loggers": { + "quart.app": { + "level": "ERROR", + }, + }, + } + ) + + self.server.run(host=host, port=port, debug=debug, **kwargs) + + def make_response( + self, + data: str | bytes | bytearray, + mimetype: str | None = None, + content_type: str | None = None, + status=None, + ): + if Response is None: + raise RuntimeError("Quart not installed; cannot generate Response") + return Response( + data, mimetype=mimetype, content_type=content_type, status=status + ) + + def jsonify(self, obj): + return jsonify(obj) + + def serve_component_suites( + self, dash_app: Dash, package_name: str, fingerprinted_path: str + ): # noqa: ARG002 unused req preserved for interface parity + path_in_pkg, has_fingerprint = check_fingerprint(fingerprinted_path) + _validate.validate_js_path(dash_app.registered_paths, package_name, path_in_pkg) + extension = "." + path_in_pkg.split(".")[-1] + mimetype = mimetypes.types_map.get(extension, "application/octet-stream") + package = sys.modules[package_name] + dash_app.logger.debug( + "serving -- package: %s[%s] resource: %s => location: %s", + package_name, + getattr(package, "__version__", "unknown"), + path_in_pkg, + package.__path__, + ) + data = pkgutil.get_data(package_name, path_in_pkg) + headers = {} + if has_fingerprint: + headers["Cache-Control"] = "public, max-age=31536000" + + if Response is None: + raise RuntimeError("Quart not installed; cannot generate Response") + return Response(data, content_type=mimetype, headers=headers) + + def setup_component_suites(self, dash_app: Dash): + async def serve(package_name, fingerprinted_path): + return self.serve_component_suites( + dash_app, package_name, fingerprinted_path + ) + + # pylint: disable=protected-access + dash_app._add_url( + "_dash-component-suites//", + serve, + ) + + def _create_redirect_function(self, redirect_to): + def _redirect(): + return redirect(redirect_to, code=301) + + return _redirect + + def add_redirect_rule(self, app, fullname, path): + self.server.add_url_rule( + fullname, + fullname, + self._create_redirect_function(app.get_relative_path(path)), + ) + + # pylint: disable=unused-argument + def serve_callback(self, dash_app: Dash): # type: ignore[name-defined] Quart always async + async def _dispatch(): + adapter = QuartRequestAdapter() + body = await adapter.get_json() + # pylint: disable=protected-access + cb_ctx = dash_app._initialize_context(body) + # pylint: disable=protected-access + func = dash_app._prepare_callback(cb_ctx, body) + # pylint: disable=protected-access + args = dash_app._inputs_to_vals(cb_ctx.inputs_list + cb_ctx.states_list) + ctx = copy_context() + # pylint: disable=protected-access + partial_func = dash_app._execute_callback( + func, args, cb_ctx.outputs_list, cb_ctx + ) + response_data = ctx.run(partial_func) + if inspect.iscoroutine(response_data): # if user callback is async + response_data = await response_data + return cb_ctx.dash_response.set_response(data=response_data) # type: ignore[arg-type] + + return _dispatch + + def register_callback_api_routes( + self, callback_api_paths: _t.Dict[str, _t.Callable[..., _t.Any]] + ): + """ + Register callback API endpoints on the Quart app. + Each key in callback_api_paths is a route, each value is a handler (sync or async). + The view function parses the JSON body and passes it to the handler. + """ + for path, handler in callback_api_paths.items(): + endpoint = f"dash_callback_api_{path}" + route = path if path.startswith("/") else f"/{path}" + methods = ["POST"] + + def _make_view_func(handler): + if inspect.iscoroutinefunction(handler): + + async def async_view_func(*args, **kwargs): + if request is None: + raise RuntimeError( + "Quart not installed; request unavailable" + ) + data = await request.get_json() + result = await handler(**data) if data else await handler() + return jsonify(result) # type: ignore[arg-type] + + return async_view_func + + async def sync_view_func(*args, **kwargs): + if request is None: + raise RuntimeError("Quart not installed; request unavailable") + data = await request.get_json() + result = handler(**data) if data else handler() + return jsonify(result) # type: ignore[arg-type] + + return sync_view_func + + view_func = _make_view_func(handler) + self.server.add_url_rule( + route, endpoint=endpoint, view_func=view_func, methods=methods + ) + + def enable_compression(self) -> None: + try: + import quart_compress # pylint: disable=import-outside-toplevel + + Compress = quart_compress.Compress + Compress(self.server) + _flask_compress_version = parse_version( + _get_distribution_version("quart_compress") + ) + if not hasattr( + self.server.config, "COMPRESS_ALGORITHM" + ) and _flask_compress_version >= parse_version("1.6.0"): + self.server.config["COMPRESS_ALGORITHM"] = ["gzip"] + except ImportError as error: + raise ImportError( + "To use the compress option, you need to install quart_compress." + ) from error + + +class QuartRequestAdapter(RequestAdapter): + def __init__(self) -> None: + self._request = request # type: ignore[assignment] + if self._request is None: + raise RuntimeError("Quart not installed; cannot access request context") + + @property + def context(self): + if not has_request_context(): + raise RuntimeError("No active request in context") + return quart_g + + @property + def request(self) -> _t.Any: + return self._request + + @property + def root(self): + return self.request.root_url + + @property + def args(self): + return self.request.args + + @property + def is_json(self): + return self.request.is_json + + @property + def cookies(self): + return self.request.cookies + + @property + def headers(self): + return self.request.headers + + @property + def full_path(self): + return self.request.full_path + + @property + def url(self): + return str(self.request.url) + + @property + def remote_addr(self): + return self.request.remote_addr + + @property + def origin(self): + return self.request.headers.get("origin") + + @property + def path(self): + return self.request.path + + async def get_json(self): # pylint: disable=W0236 + # TODO consider using a sync wraper + return await self.request.get_json() diff --git a/dash/backends/_utils.py b/dash/backends/_utils.py new file mode 100644 index 0000000000..1191d21038 --- /dev/null +++ b/dash/backends/_utils.py @@ -0,0 +1,108 @@ +import traceback +import re + + +def format_traceback_html(error, error_handling_mode, title, backend): + tb = error.__traceback__ + errors = traceback.format_exception(type(error), error, tb) + pass_errs = [] + callback_handled = False + for err in errors: + if error_handling_mode == "prune": + if not callback_handled: + if "callback invoked" in str(err) and "_callback.py" in str(err): + callback_handled = True + continue + pass_errs.append(err) + formatted_tb = "".join(pass_errs) + error_type = type(error).__name__ + error_msg = str(error) + # Parse traceback lines to group by file + file_cards = [] + pattern = re.compile(r' File "(.+)", line (\d+), in (\w+)') + lines = formatted_tb.split("\n") + current_file = None + card_lines = [] + for line in lines[:-1]: # Skip the last line (error message) + match = pattern.match(line) + if match: + if current_file and card_lines: + file_cards.append((current_file, card_lines)) + current_file = ( + f"{match.group(1)} (line {match.group(2)}, in {match.group(3)})" + ) + card_lines = [line] + elif current_file: + card_lines.append(line) + if current_file and card_lines: + file_cards.append((current_file, card_lines)) + cards_html = "" + for filename, card in file_cards: + cards_html += ( + f""" +
+
{filename}
+
"""
+            + "\n".join(card)
+            + """
+
+ """ + ) + html = f""" + + + + {error_type}: {error_msg} // {title} + + + +
+

{error_type}

+
+

{error_type}: {error_msg}

+
+

Traceback (most recent call last)

+ {cards_html} +
{error_type}: {error_msg}
+
+

This is the Copy/Paste friendly version of the traceback.

+ +
+
+ The debugger caught an exception in your Dash application. You can now + look at the traceback which led to the error. +
+
+ Brought to you by DON'T PANIC, your + friendly {backend} powered traceback interpreter. +
+
+ + + """ + return html diff --git a/dash/backends/base_server.py b/dash/backends/base_server.py new file mode 100644 index 0000000000..f7211f44a6 --- /dev/null +++ b/dash/backends/base_server.py @@ -0,0 +1,374 @@ +"""Base server abstractions for Dash backend implementations. + +This module provides abstract base classes and protocols that define the interface +for different web server backends (Flask, Quart, FastAPI, etc.) to integrate with Dash. +""" +from abc import ABC, abstractmethod +from typing import Any, Dict, Type, TypeVar, Generic, Protocol, TYPE_CHECKING + + +if TYPE_CHECKING: + import dash + + +class _ServerCallable(Protocol): # pylint: disable=too-few-public-methods + """Protocol for callable server instances. + + Defines the interface for server objects that can be called as WSGI/ASGI applications. + """ + + def __call__(self, *args: Any, **kwds: Any) -> Any: + raise NotImplementedError + + +ServerType = TypeVar("ServerType", bound=_ServerCallable) + + +class RequestAdapter(ABC): + """Abstract adapter for normalizing HTTP request objects across different server backends. + + This adapter provides a unified interface for accessing request data regardless of + the underlying web framework (Flask, Quart, FastAPI, etc.). Concrete implementations + wrap framework-specific request objects and expose their data through these properties. + """ + + def __call__(self) -> "RequestAdapter": + return self + + @property + @abstractmethod + def context(self) -> Any: # pragma: no cover - interface + """Get the framework-specific request context object.""" + raise NotImplementedError() + + # Properties to be implemented in concrete adapters + @property # pragma: no cover - interface + @abstractmethod + def root(self) -> str: + """Get the application root path.""" + raise NotImplementedError() + + @property # pragma: no cover - interface + @abstractmethod + def args(self): + """Get the request query string arguments.""" + raise NotImplementedError() + + @abstractmethod # kept as method (may be sync or async) + def get_json(self): # pragma: no cover - interface + """Get the parsed JSON body of the request. + + May be synchronous or asynchronous depending on the backend. + """ + raise NotImplementedError() + + @property # pragma: no cover - interface + @abstractmethod + def is_json(self) -> bool: + """Check if the request has a JSON content type.""" + raise NotImplementedError() + + @property # pragma: no cover - interface + @abstractmethod + def cookies(self): + """Get the request cookies.""" + raise NotImplementedError() + + @property # pragma: no cover - interface + @abstractmethod + def headers(self): + """Get the request headers.""" + raise NotImplementedError() + + @property # pragma: no cover - interface + @abstractmethod + def full_path(self) -> str: + """Get the full request path including query string.""" + raise NotImplementedError() + + @property # pragma: no cover - interface + @abstractmethod + def url(self) -> str: + """Get the full request URL.""" + raise NotImplementedError() + + @property # pragma: no cover - interface + @abstractmethod + def remote_addr(self): + """Get the remote client IP address.""" + raise NotImplementedError() + + @property # pragma: no cover - interface + @abstractmethod + def origin(self): + """Get the Origin header value.""" + raise NotImplementedError() + + @property # pragma: no cover - interface + @abstractmethod + def path(self) -> str: + """Get the request path without query string.""" + raise NotImplementedError() + + +class ResponseAdapter: + """Adapter for server response objects to allow setting data.""" + + def __init__(self): + # Accept a pre-made response object + self._headers = {} + self._cookies = {} + + @property + def callback_response(self): + """Get the response object to be returned from a callback.""" + # This method should be overridden in concrete implementations to return the appropriate response object + raise NotImplementedError() + + def set_cookie(self, key, value="", **kwargs): + """Set a cookie in the response (like Flask's set_cookie).""" + # Store as a tuple: (value, kwargs) + self._cookies[key] = (value, kwargs) + + def append_header(self, key, value): + """Add a header to the response (like Flask's headers.add).""" + # Allow multiple values per header key + if key in self._headers: + if isinstance(self._headers[key], list): + self._headers[key].append(value) + else: + self._headers[key] = [self._headers[key], value] + else: + self._headers[key] = value + + def set_header(self, key, value): + """Set a header to the response.""" + self._headers[key] = [value] + + def set_response(self, **kwargs): + """Set the response data if supported by the response object.""" + raise NotImplementedError() + + +class BaseDashServer(ABC, Generic[ServerType]): + """Abstract base class for Dash server backend implementations. + + This class defines the interface that all server backends must implement to + work with Dash. Concrete implementations exist for Flask, Quart, FastAPI, and + other web frameworks. + + Attributes: + server_type: String identifier for the server backend (e.g., 'flask', 'quart') + server: The underlying server instance + config: Configuration dictionary for the server + request_adapter: RequestAdapter class for normalizing requests + """ + + server_type: str + server: ServerType + config: Dict[str, Any] + request_adapter: Type[RequestAdapter] + response_adapter: Type[ResponseAdapter] + + def __init__(self, server: ServerType) -> None: + """Initialize the server wrapper. + + Args: + server: The underlying server instance to wrap + """ + super().__init__() + self.server = server + + def __call__(self, *args, **kwargs) -> Any: + """Make the server wrapper callable as a WSGI/ASGI application. + + Delegates to the underlying server instance. + """ + # Default: WSGI + return self.server(*args, **kwargs) + + @staticmethod + @abstractmethod + def create_app( + name: str = "__main__", config=None + ) -> Any: # pragma: no cover - interface + """Create a new server application instance. + + Args: + name: Application name, defaults to '__main__' + config: Configuration dictionary or object + + Returns: + The server application instance + """ + + @abstractmethod + def register_assets_blueprint( + self, blueprint_name: str, assets_url_path: str, assets_folder: str + ) -> None: # pragma: no cover - interface + """Register a blueprint/router for serving static assets. + + Args: + blueprint_name: Name for the assets blueprint + assets_url_path: URL path prefix for assets + assets_folder: Filesystem path to the assets folder + """ + + @abstractmethod + def register_error_handlers(self) -> None: # pragma: no cover - interface + """Register error handlers for common HTTP errors.""" + + @abstractmethod + def add_url_rule( + self, rule: str, view_func, endpoint=None, methods=None + ) -> None: # pragma: no cover - interface + """Add a URL routing rule. + + Args: + rule: URL pattern/route + view_func: View function to handle the route + endpoint: Optional endpoint name + methods: Optional list of HTTP methods (e.g., ['GET', 'POST']) + """ + + @abstractmethod + def before_request(self, func) -> None: # pragma: no cover - interface + """Register a function to run before each request. + + Args: + func: Function to execute before request handling + """ + + @abstractmethod + def after_request(self, func) -> None: # pragma: no cover - interface + """Register a function to run after each request. + + Args: + func: Function to execute after request handling + """ + + @abstractmethod + def has_request_context(self) -> bool: # pragma: no cover - interface + """Check if currently executing within a request context. + + Returns: + True if in request context, False otherwise + """ + + @abstractmethod + def run( + self, dash_app, host: str, port: int, debug: bool, **kwargs + ) -> None: # pragma: no cover - interface + """Start the development server. + + Args: + dash_app: The Dash application instance + host: Hostname to bind to + port: Port number to bind to + debug: Enable debug mode + **kwargs: Additional server-specific arguments + """ + + @abstractmethod + def make_response( + self, + data, + mimetype=None, + content_type=None, + status=None, + ) -> Any: # pragma: no cover - interface + """Create an HTTP response object. + + Args: + data: Response body data + mimetype: MIME type of the response + content_type: Content-Type header value + status: HTTP status code + + Returns: + Server-specific response object + """ + + @abstractmethod + def jsonify(self, obj) -> Any: # pragma: no cover - interface + """Convert an object to a JSON response. + + Args: + obj: Object to serialize to JSON + + Returns: + JSON response object + """ + + @abstractmethod + def enable_compression(self) -> None: # pragma: no cover - interface + """Enable HTTP compression for responses.""" + + @abstractmethod + def register_prune_error_handler(self, secret: str, prune_errors: bool) -> None: + """Register handler for pruning error stack traces. + + Args: + secret: Secret key for error handling + prune_errors: Whether to prune stack traces in errors + """ + + @abstractmethod + def register_timing_hooks(self, first_run: bool) -> None: + """Register hooks for timing request/response cycles. + + Args: + first_run: Whether this is the first run of the application + """ + + @abstractmethod + def register_callback_api_routes(self, callback_api_paths): + """Register routes for Dash callback API endpoints. + + Args: + callback_api_paths: Paths for callback API endpoints + """ + + @abstractmethod + def setup_component_suites(self, dash_app: "dash.Dash") -> str: + """Set up routes for serving component JavaScript bundles. + + Args: + dash_app: The Dash application instance + + Returns: + Base path for component suites + """ + + @abstractmethod + def serve_callback(self, dash_app: "dash.Dash"): + """Set up the callback handling endpoint. + + Args: + dash_app: The Dash application instance + """ + + @abstractmethod + def setup_index(self, dash_app: "dash.Dash"): + """Set up the index/root route for serving the main application. + + Args: + dash_app: The Dash application instance + """ + + @abstractmethod + def setup_catchall(self, dash_app: "dash.Dash"): + """Set up the catchall route for client-side routing. + + Args: + dash_app: The Dash application instance + """ + + def setup_backend(self, dash_app: "dash.Dash"): + """Perform any additional backend-specific setup. + + Override this method in concrete implementations to provide custom setup logic. + + Args: + dash_app: The Dash application instance + """ diff --git a/dash/dash-renderer/src/components/error/FrontEnd/FrontEndError.react.js b/dash/dash-renderer/src/components/error/FrontEnd/FrontEndError.react.js index 176cb2c6f8..db4c6ddd2b 100644 --- a/dash/dash-renderer/src/components/error/FrontEnd/FrontEndError.react.js +++ b/dash/dash-renderer/src/components/error/FrontEnd/FrontEndError.react.js @@ -121,13 +121,18 @@ function BackendError({error, base}) { const MAX_MESSAGE_LENGTH = 40; /* eslint-disable no-inline-comments */ function UnconnectedErrorContent({error, base}) { + // Helper to detect full HTML document + const isFullHtmlDoc = + typeof error.html === 'string' && + error.html.trim().toLowerCase().startsWith(' - {/* - * 40 is a rough heuristic - if longer than 40 then the - * message might overflow into ellipses in the title above & - * will need to be displayed in full in this error body - */} + {/* Frontend error message */} {typeof error.message !== 'string' || error.message.length < MAX_MESSAGE_LENGTH ? null : (
@@ -137,6 +142,7 @@ function UnconnectedErrorContent({error, base}) {
)} + {/* Frontend stack trace */} {typeof error.stack !== 'string' ? null : (
@@ -149,7 +155,6 @@ function UnconnectedErrorContent({error, base}) { browser's console.) - {error.stack.split('\n').map((line, i) => (

{line}

))} @@ -157,24 +162,30 @@ function UnconnectedErrorContent({error, base}) {
)} - {/* Backend Error */} - {typeof error.html !== 'string' ? null : error.html - .substring(0, '
- {/* Embed werkzeug debugger in an iframe to prevent - CSS leaking - werkzeug HTML includes a bunch - of CSS on base html elements like `` - */}
- ) : ( + ) : isHtmlFragment ? ( + // Backend error: HTML fragment +
+
+
+ ) : typeof error.html === 'string' ? ( + // Backend error: plain text
-
{error.html}
+
+
{error.html}
+
- )} + ) : null}
); } diff --git a/dash/dash.py b/dash/dash.py index 03bdec5498..71f7f33cb4 100644 --- a/dash/dash.py +++ b/dash/dash.py @@ -5,7 +5,6 @@ import inspect import importlib import warnings -from contextvars import copy_context from importlib.machinery import ModuleSpec from importlib.util import find_spec from importlib import metadata @@ -13,24 +12,18 @@ import threading import re import logging -import time import mimetypes import hashlib import base64 -import traceback from urllib.parse import urlparse from typing import Any, Callable, Dict, Optional, Union, Sequence, Literal, List -import asyncio -import flask - -from importlib_metadata import version as _get_distribution_version +import traceback from dash import dcc from dash import html from dash import dash_table - -from .fingerprint import build_fingerprint, check_fingerprint +from .fingerprint import build_fingerprint from .resources import Scripts, Css from .dependencies import ( Input, @@ -39,11 +32,10 @@ ) from .development.base_component import ComponentRegistry from .exceptions import ( - PreventUpdate, - InvalidResourceError, ProxyError, DuplicateCallback, ) +from .backends import get_backend from .version import __version__ from ._configs import get_combined_config, pathname_configs, pages_folder_config from ._utils import ( @@ -59,8 +51,8 @@ convert_to_AttributeDict, gen_salt, hooks_to_js_object, - parse_version, get_caller_name, + get_root_path, ) from . import _callback from . import _get_paths @@ -68,10 +60,12 @@ from . import _validate from . import _watch from . import _get_app +from . import backends -from ._get_app import with_app_context, with_app_context_async, with_app_context_factory +from ._get_app import with_app_context, with_app_context_factory from ._grouping import map_grouping, grouping_len, update_args_group from ._obsolete import ObsoleteChecker +from ._callback_context import callback_context from . import _pages from ._pages import ( @@ -250,6 +244,12 @@ class Dash(ObsoleteChecker): ``flask.Flask``: use this pre-existing Flask server. :type server: boolean or flask.Flask + :param backend: The backend to use for the Dash app. Can be a string + (name of the backend) or a backend class. Default is None, which + selects the Flask backend. Currently, "flask", "fastapi", and "quart" backends + are supported. + :type backend: string or type + :param assets_folder: a path, relative to the current working directory, for extra files to be used in the browser. Default ``'assets'``. All .js and .css files will be loaded immediately unless excluded by @@ -426,16 +426,17 @@ class Dash(ObsoleteChecker): _plotlyjs_url: str STARTUP_ROUTES: list = [] - server: flask.Flask + server: Any # Layout is a complex type which can be many things _layout: Any _extra_components: Any - def __init__( # pylint: disable=too-many-statements + def __init__( # pylint: disable=too-many-statements, too-many-branches self, name: Optional[str] = None, - server: Union[bool, flask.Flask] = True, + server: Union[bool, Callable[[], Any]] = True, + backend: Union[str, type, None] = None, assets_folder: str = "assets", pages_folder: str = "pages", use_pages: Optional[bool] = None, @@ -475,35 +476,40 @@ def __init__( # pylint: disable=too-many-statements **obsolete, ): - if use_async is None: - try: - import asgiref # type: ignore[import-not-found] # pylint: disable=unused-import, import-outside-toplevel # noqa - - use_async = True - except ImportError: - pass - elif use_async: - try: - import asgiref # type: ignore[import-not-found] # pylint: disable=unused-import, import-outside-toplevel # noqa - except ImportError as exc: - raise Exception( - "You are trying to use dash[async] without having installed the requirements please install via: `pip install dash[async]`" - ) from exc - + use_async = _validate.check_async(use_async) _validate.check_obsolete(obsolete) caller_name: str = name if name is not None else get_caller_name() - # We have 3 cases: server is either True (we create the server), False - # (defer server creation) or a Flask app instance (we use their server) - if isinstance(server, flask.Flask): - self.server = server + # Determine backend + if backend is None: + backend_cls = get_backend("flask") + elif isinstance(backend, str): + backend_cls = get_backend(backend) + elif isinstance(backend, type): + backend_cls = backend + else: + raise ValueError("Invalid backend argument") + + # Determine server and backend instance + if server not in (None, True, False): + # User provided a server instance (e.g., Flask, Quart, FastAPI) + inferred_backend = backends.get_server_type(server) + _validate.check_backend(backend, inferred_backend) + backend_cls = get_backend(inferred_backend) if name is None: caller_name = getattr(server, "name", caller_name) - elif isinstance(server, bool): - self.server = flask.Flask(caller_name) if server else None # type: ignore + + self.backend = backend_cls(server) + self.server = server + backends.backend = self.backend # type: ignore + backends.request_adapter = self.backend.request_adapter # type: ignore else: - raise ValueError("server must be a Flask app or a boolean") + # No server instance provided, create backend and let backend create server + self.server = backend_cls.create_app(caller_name) # type: ignore + self.backend = backend_cls(self.server) + backends.backend = self.backend + backends.request_adapter = self.backend.request_adapter # type: ignore base_prefix, routes_prefix, requests_prefix = pathname_configs( url_base_pathname, routes_pathname_prefix, requests_pathname_prefix @@ -512,7 +518,7 @@ def __init__( # pylint: disable=too-many-statements self.config = AttributeDict( name=caller_name, assets_folder=os.path.join( - flask.helpers.get_root_path(caller_name), assets_folder + get_root_path(caller_name), assets_folder ), # type: ignore assets_url_path=assets_url_path, assets_ignore=assets_ignore, @@ -635,7 +641,7 @@ def __init__( # pylint: disable=too-many-statements # tracks internally if a function already handled at least one request. self._got_first_request = {"pages": False, "setup_server": False} - if self.server is not None: + if server: self.init_app() self.logger.setLevel(logging.INFO) @@ -681,11 +687,15 @@ def _setup_hooks(self): if self._hooks.get_hooks("error"): self._on_error = self._hooks.HookErrorHandler(self._on_error) - def init_app(self, app: Optional[flask.Flask] = None, **kwargs) -> None: - """Initialize the parts of Dash that require a flask app.""" - + def init_app(self, app: Optional[Any] = None, **kwargs) -> None: config = self.config - + config.unset_read_only( + [ + "url_base_pathname", + "routes_pathname_prefix", + "requests_pathname_prefix", + ] + ) config.update(kwargs) config.set_read_only( [ @@ -695,91 +705,69 @@ def init_app(self, app: Optional[flask.Flask] = None, **kwargs) -> None: ], "Read-only: can only be set in the Dash constructor or during init_app()", ) - if app is not None: self.server = app - bp_prefix = config.routes_pathname_prefix.replace("/", "_").replace(".", "_") assets_blueprint_name = f"{bp_prefix}dash_assets" - - self.server.register_blueprint( - flask.Blueprint( - assets_blueprint_name, - config.name, - static_folder=self.config.assets_folder, - static_url_path=config.routes_pathname_prefix - + self.config.assets_url_path.lstrip("/"), - ) + self.backend.register_assets_blueprint( + assets_blueprint_name, + config.routes_pathname_prefix + self.config.assets_url_path.lstrip("/"), + self.config.assets_folder, ) - if config.compress: - try: - # pylint: disable=import-outside-toplevel - from flask_compress import Compress # type: ignore - - # gzip - Compress(self.server) + self.backend.enable_compression() # type: ignore - _flask_compress_version = parse_version( - _get_distribution_version("flask_compress") - ) - - if not hasattr( - self.server.config, "COMPRESS_ALGORITHM" - ) and _flask_compress_version >= parse_version("1.6.0"): - # flask-compress==1.6.0 changed default to ['br', 'gzip'] - # and non-overridable default compression with Brotli is - # causing performance issues - self.server.config["COMPRESS_ALGORITHM"] = ["gzip"] - except ImportError as error: - raise ImportError( - "To use the compress option, you need to install dash[compress]" - ) from error - - @self.server.errorhandler(PreventUpdate) def _handle_error(_): """Handle a halted callback and return an empty 204 response.""" return "", 204 - self.server.before_request(self._setup_server) - + # To-Do add error handlers for these two scenarios + # add handler for halted callbacks + # self.backend.before_request(_handle_error) # add a handler for components suites errors to return 404 - self.server.errorhandler(InvalidResourceError)(self._invalid_resources_handler) + # self.server.errorhandler(InvalidResourceError)(self._invalid_resources_handler) + self.backend.register_error_handlers() + self.backend.before_request(self._setup_server) + self.backend.setup_backend(self) self._setup_routes() - _get_app.APP = self self.enable_pages() - self._setup_plotlyjs() def _add_url(self, name: str, view_func: RouteCallable, methods=("GET",)) -> None: full_name = self.config.routes_pathname_prefix + name - - self.server.add_url_rule( - full_name, view_func=view_func, endpoint=full_name, methods=list(methods) + self.backend.add_url_rule( + full_name, + view_func=view_func, + endpoint=full_name, + methods=list(methods), ) - - # record the url in Dash.routes so that it can be accessed later - # e.g. for adding authentication with flask_login self.routes.append(full_name) - def _setup_routes(self): - self._add_url( - "_dash-component-suites//", - self.serve_component_suites, + def _serve_default_favicon(self): + return self.backend.make_response( + pkgutil.get_data("dash", "favicon.ico"), content_type="image/x-icon" ) + + def _setup_routes(self): + self.backend.setup_component_suites(self) self._add_url("_dash-layout", self.serve_layout) self._add_url("_dash-dependencies", self.dependencies) - if self._use_async: - self._add_url("_dash-update-component", self.async_dispatch, ["POST"]) - else: - self._add_url("_dash-update-component", self.dispatch, ["POST"]) + self._add_url( + "_dash-update-component", + self.backend.serve_callback(self), + ["POST"], + ) self._add_url("_reload-hash", self.serve_reload_hash) - self._add_url("_favicon.ico", self._serve_default_favicon) + self._add_url( + "_favicon.ico", + self._serve_default_favicon, # pylint: disable=protected-access + ) if self.config.health_endpoint is not None: self._add_url(self.config.health_endpoint, self.serve_health) - self._add_url("", self.index) + self.backend.setup_index(self) + self.backend.setup_catchall(self) if jupyter_dash.active: self._add_url( @@ -793,9 +781,6 @@ def _setup_routes(self): hook.data["methods"], ) - # catch-all for front-end routes, used by dcc.Location - self._add_url("", self.index) - def setup_apis(self): """ Register API endpoints for all callbacks defined using `dash.callback`. @@ -819,30 +804,8 @@ def setup_apis(self): ) self.callback_api_paths[k] = _callback.GLOBAL_API_PATHS.pop(k) - def make_parse_body(func): - def _parse_body(): - if flask.request.is_json: - data = flask.request.get_json() - return flask.jsonify(func(**data)) - return flask.jsonify({}) - - return _parse_body - - def make_parse_body_async(func): - async def _parse_body_async(): - if flask.request.is_json: - data = flask.request.get_json() - result = await func(**data) - return flask.jsonify(result) - return flask.jsonify({}) - - return _parse_body_async - - for path, func in self.callback_api_paths.items(): - if inspect.iscoroutinefunction(func): - self._add_url(path, make_parse_body_async(func), ["POST"]) - else: - self._add_url(path, make_parse_body(func), ["POST"]) + # Delegate to the server factory for route registration + self.backend.register_callback_api_routes(self.callback_api_paths) def _setup_plotlyjs(self): # pylint: disable=import-outside-toplevel @@ -914,7 +877,7 @@ def serve_layout(self): layout = hook(layout) # TODO - Set browser cache limit - pass hash into frontend - return flask.Response( + return self.backend.make_response( to_json(layout), mimetype="application/json", ) @@ -992,7 +955,7 @@ def serve_reload_hash(self): _reload.hard = False _reload.changed_assets = [] - return flask.jsonify( + return self.backend.jsonify( { "reloadHash": _hash, "hard": hard, @@ -1006,7 +969,7 @@ def serve_health(self): Health check endpoint for monitoring Dash server status. Returns a simple "OK" response with HTTP 200 status. """ - return flask.Response("OK", status=200, mimetype="text/plain") + return self.backend.make_response("OK", status=200, mimetype="text/plain") def get_dist(self, libraries: Sequence[str]) -> list: dists = [] @@ -1116,9 +1079,11 @@ def _generate_css_dist_html(self): return "\n".join( [ - format_tag("link", link, opened=True) - if isinstance(link, dict) - else f'' + ( + format_tag("link", link, opened=True) + if isinstance(link, dict) + else f'' + ) for link in (external_links + links) ] ) @@ -1172,9 +1137,11 @@ def _generate_scripts_html(self) -> str: return "\n".join( [ - format_tag("script", src) - if isinstance(src, dict) - else f'' + ( + format_tag("script", src) + if isinstance(src, dict) + else f'' + ) for src in srcs ] + [f"" for src in self._inline_scripts] @@ -1205,58 +1172,18 @@ def _generate_meta(self): return meta_tags + self.config.meta_tags - # Serve the JS bundles for each package - def serve_component_suites(self, package_name, fingerprinted_path): - path_in_pkg, has_fingerprint = check_fingerprint(fingerprinted_path) - - _validate.validate_js_path(self.registered_paths, package_name, path_in_pkg) - - extension = "." + path_in_pkg.split(".")[-1] - mimetype = mimetypes.types_map.get(extension, "application/octet-stream") - - package = sys.modules[package_name] - self.logger.debug( - "serving -- package: %s[%s] resource: %s => location: %s", - package_name, - package.__version__, - path_in_pkg, - package.__path__, - ) - - response = flask.Response( - pkgutil.get_data(package_name, path_in_pkg), mimetype=mimetype - ) - - if has_fingerprint: - # Fingerprinted resources are good forever (1 year) - # No need for ETag as the fingerprint changes with each build - response.cache_control.max_age = 31536000 # 1 year - else: - # Non-fingerprinted resources are given an ETag that - # will be used / check on future requests - response.add_etag() - tag = response.get_etag()[0] - - request_etag = flask.request.headers.get("If-None-Match") - - if f'"{tag}"' == request_etag: - response = flask.Response(None, status=304) - - return response - - @with_app_context - def index(self, *args, **kwargs): # pylint: disable=unused-argument + def index(self, *_args, **_kwargs): scripts = self._generate_scripts_html() css = self._generate_css_dist_html() config = self._generate_config_html() metas = self._generate_meta() renderer = self._generate_renderer() - - # use self.title instead of app.config.title for backwards compatibility title = self.title + # Refactored: direct access to global request adapter + request = backends.backend.request_adapter() - if self.use_pages and self.config.include_pages_meta: - metas = _page_meta_tags(self) + metas + if self.use_pages and self.config.include_pages_meta and request: + metas = _page_meta_tags(self, request) + metas if self._favicon: favicon_mod_time = os.path.getmtime( @@ -1360,7 +1287,7 @@ def interpolate_index(self, **kwargs): @with_app_context def dependencies(self): - return flask.Response( + return self.backend.make_response( to_json(self._callback_list), content_type="application/json", ) @@ -1463,9 +1390,13 @@ def callback(self, *_args, **_kwargs) -> Callable[..., Any]: **_kwargs, ) + def _inputs_to_vals(self, inputs): + return inputs_to_vals(inputs) + # pylint: disable=R0915 def _initialize_context(self, body): """Initialize the global context for the request.""" + adapter = backends.backend.request_adapter() g = AttributeDict({}) g.inputs_list = body.get("inputs", []) g.states_list = body.get("state", []) @@ -1476,12 +1407,13 @@ def _initialize_context(self, body): {"prop_id": x, "value": g.input_values.get(x)} for x in body.get("changedPropIds", []) ] - g.dash_response = flask.Response(mimetype="application/json") - g.cookies = dict(**flask.request.cookies) - g.headers = dict(**flask.request.headers) - g.path = flask.request.full_path - g.remote = flask.request.remote_addr - g.origin = flask.request.origin + g.dash_response = self.backend.response_adapter() + g.cookies = dict(adapter.cookies) + g.headers = dict(adapter.headers) + g.args = adapter.args + g.path = adapter.full_path + g.remote = adapter.remote_addr + g.origin = adapter.origin g.updated_props = {} return g @@ -1545,11 +1477,6 @@ def _prepare_grouping(self, data_list, indices): def _execute_callback(self, func, args, outputs_list, g): """Execute the callback with the prepared arguments.""" - g.cookies = dict(**flask.request.cookies) - g.headers = dict(**flask.request.headers) - g.path = flask.request.full_path - g.remote = flask.request.remote_addr - g.origin = flask.request.origin g.custom_data = AttributeDict({}) for hook in self._hooks.get_hooks("custom_data"): @@ -1568,47 +1495,6 @@ def _execute_callback(self, func, args, outputs_list, g): ) return partial_func - @with_app_context_async - async def async_dispatch(self): - body = flask.request.get_json() - g = self._initialize_context(body) - func = self._prepare_callback(g, body) - args = inputs_to_vals(g.inputs_list + g.states_list) - - ctx = copy_context() - partial_func = self._execute_callback(func, args, g.outputs_list, g) - if asyncio.iscoroutine(func): - response_data = await ctx.run(partial_func) - else: - response_data = ctx.run(partial_func) - - if asyncio.iscoroutine(response_data): - response_data = await response_data - - g.dash_response.set_data(response_data) - return g.dash_response - - @with_app_context - def dispatch(self): - body = flask.request.get_json() - g = self._initialize_context(body) - func = self._prepare_callback(g, body) - args = inputs_to_vals(g.inputs_list + g.states_list) - - ctx = copy_context() - partial_func = self._execute_callback(func, args, g.outputs_list, g) - response_data = ctx.run(partial_func) - - if asyncio.iscoroutine(response_data): - raise Exception( - "You are trying to use a coroutine without dash[async]. " - "Please install the dependencies via `pip install dash[async]` and ensure " - "that `use_async=False` is not being passed to the app." - ) - - g.dash_response.set_data(response_data) - return g.dash_response - def _setup_server(self): if self._got_first_request["setup_server"]: return @@ -1682,7 +1568,7 @@ def _setup_server(self): manager=manager, ) def cancel_call(*_): - job_ids = flask.request.args.getlist("cancelJob") + job_ids = callback_context.args.getlist("cancelJob") executor = _callback.context_value.get().background_callback_manager if job_ids: for job_id in job_ids: @@ -1751,12 +1637,6 @@ def _walk_assets_directory(self): def _invalid_resources_handler(err): return err.args[0], 404 - @staticmethod - def _serve_default_favicon(): - return flask.Response( - pkgutil.get_data("dash", "favicon.ico"), content_type="image/x-icon" - ) - def csp_hashes(self, hash_algorithm="sha256") -> Sequence[str]: """Calculates CSP hashes (sha + base64) of all inline scripts, such that one of the biggest benefits of CSP (disallowing general inline scripts) @@ -2003,6 +1883,7 @@ def enable_dev_tools( # pylint: disable=too-many-branches dev_tools_silence_routes_logging: Optional[bool] = None, dev_tools_disable_version_check: Optional[bool] = None, dev_tools_prune_errors: Optional[bool] = None, + first_run: bool = True, ) -> bool: """Activate the dev tools, called by `run`. If your application is served by wsgi and you want to activate the dev tools, you can call @@ -2062,9 +1943,10 @@ def enable_dev_tools( # pylint: disable=too-many-branches env: ``DASH_HOT_RELOAD_MAX_RETRY`` :type dev_tools_hot_reload_max_retry: int - :param dev_tools_silence_routes_logging: Silence the `werkzeug` logger, - will remove all routes logging. Enabled with debugging by default - because hot reload hash checks generate a lot of requests. + :param dev_tools_silence_routes_logging: Silence the route logging for the + web server (werkzeug for Flask, hypercorn for Quart, uvicorn for FastAPI). + Enabled with debugging by default because hot reload hash checks generate + a lot of requests. env: ``DASH_SILENCE_ROUTES_LOGGING`` :type dev_tools_silence_routes_logging: bool @@ -2099,7 +1981,18 @@ def enable_dev_tools( # pylint: disable=too-many-branches ) if dev_tools.silence_routes_logging: - logging.getLogger("werkzeug").setLevel(logging.ERROR) + # Silence route logging based on backend type + backend_type = getattr(self.backend, "server_type", "flask") + if backend_type == "flask": + logging.getLogger("werkzeug").setLevel(logging.ERROR) + elif backend_type == "quart": + # Quart uses hypercorn as its ASGI server + logging.getLogger("hypercorn.access").setLevel(logging.ERROR) + logging.getLogger("hypercorn.error").setLevel(logging.ERROR) + elif backend_type == "fastapi": + # FastAPI uses uvicorn as its ASGI server + logging.getLogger("uvicorn.access").setLevel(logging.ERROR) + logging.getLogger("uvicorn.error").setLevel(logging.ERROR) if dev_tools.hot_reload: _reload = self._hot_reload @@ -2187,49 +2080,11 @@ def enable_dev_tools( # pylint: disable=too-many-branches jupyter_dash.configure_callback_exception_handling( self, dev_tools.prune_errors ) - elif dev_tools.prune_errors: - secret = gen_salt(20) - - @self.server.errorhandler(Exception) - def _wrap_errors(error): - # find the callback invocation, if the error is from a callback - # and skip the traceback up to that point - # if the error didn't come from inside a callback, we won't - # skip anything. - tb = _get_traceback(secret, error) - return tb, 500 + secret = gen_salt(20) + self.backend.register_prune_error_handler(secret, dev_tools.prune_errors) if debug and dev_tools.ui: - - def _before_request(): - flask.g.timing_information = { # pylint: disable=assigning-non-slot - "__dash_server": {"dur": time.time(), "desc": None} - } - - def _after_request(response): - timing_information = flask.g.get("timing_information", None) - if timing_information is None: - return response - - dash_total = timing_information.get("__dash_server", None) - if dash_total is not None: - dash_total["dur"] = round((time.time() - dash_total["dur"]) * 1000) - - for name, info in timing_information.items(): - value = name - if info.get("desc") is not None: - value += f';desc="{info["desc"]}"' - - if info.get("dur") is not None: - value += f";dur={info['dur']}" - - response.headers.add("Server-Timing", value) - - return response - - self.server.before_request(_before_request) - - self.server.after_request(_after_request) + self.backend.register_timing_hooks(first_run) if ( debug @@ -2392,9 +2247,10 @@ def run( env: ``DASH_HOT_RELOAD_MAX_RETRY`` :type dev_tools_hot_reload_max_retry: int - :param dev_tools_silence_routes_logging: Silence the `werkzeug` logger, - will remove all routes logging. Enabled with debugging by default - because hot reload hash checks generate a lot of requests. + :param dev_tools_silence_routes_logging: Silence the route logging for the + web server (werkzeug for Flask, hypercorn for Quart, uvicorn for FastAPI). + Enabled with debugging by default because hot reload hash checks generate + a lot of requests. env: ``DASH_SILENCE_ROUTES_LOGGING`` :type dev_tools_silence_routes_logging: bool @@ -2457,6 +2313,7 @@ def run( host = host or "127.0.0.1" else: host = host or os.getenv("HOST", "127.0.0.1") + assert host port = port or os.getenv("PORT", "8050") proxy = proxy or os.getenv("DASH_PROXY") @@ -2526,7 +2383,9 @@ def verify_url_part(served_part, url_part, part_name): server_url=jupyter_server_url, ) else: - self.server.run(host=host, port=port, debug=debug, **flask_run_options) + backends.backend.run( + dash_app=self, host=host, port=port, debug=debug, **flask_run_options + ) def enable_pages(self) -> None: if not self.use_pages: @@ -2534,8 +2393,8 @@ def enable_pages(self) -> None: if self.pages_folder: _import_layouts_from_pages(self.config.pages_folder) - @self.server.before_request - def router(): + # Async version + async def router_async(): if self._got_first_request["pages"]: return self._got_first_request["pages"] = True @@ -2544,159 +2403,152 @@ def router(): "pathname_": Input(_ID_LOCATION, "pathname"), "search_": Input(_ID_LOCATION, "search"), } - inputs.update(self.routing_callback_inputs) # type: ignore[reportCallIssue] + inputs.update(self.routing_callback_inputs) - if self._use_async: - - @self.callback( - Output(_ID_CONTENT, "children"), - Output(_ID_STORE, "data"), - inputs=inputs, - prevent_initial_call=True, - hidden=True, + @self.callback( + Output(_ID_CONTENT, "children"), + Output(_ID_STORE, "data"), + inputs=inputs, + prevent_initial_call=True, + hidden=True, + ) + async def update(pathname_, search_, **states): + query_parameters = _parse_query_string(search_) + page, path_variables = _path_to_page( + self.strip_relative_path(pathname_) ) - async def update(pathname_, search_, **states): - """ - Updates dash.page_container layout on page navigation. - Updates the stored page title which will trigger the clientside callback to update the app title - """ - - query_parameters = _parse_query_string(search_) - page, path_variables = _path_to_page( - self.strip_relative_path(pathname_) + if page == {}: + for module, page in _pages.PAGE_REGISTRY.items(): + if module.split(".")[-1] == "not_found_404": + layout = page["layout"] + title = page["title"] + break + else: + layout = html.H1("404 - Page not found") + title = self.title + else: + layout = page.get("layout", "") + title = page["title"] + + if callable(layout): + layout = await execute_async_function( + layout, + **{**(path_variables or {}), **query_parameters, **states}, + ) + if callable(title): + title = await execute_async_function( + title, **{**(path_variables or {})} ) + return layout, {"title": title} - # get layout - if page == {}: - for module, page in _pages.PAGE_REGISTRY.items(): - if module.split(".")[-1] == "not_found_404": - layout = page["layout"] - title = page["title"] - break - else: - layout = html.H1("404 - Page not found") - title = self.title - else: - layout = page.get("layout", "") - title = page["title"] + _validate.check_for_duplicate_pathnames(_pages.PAGE_REGISTRY) + _validate.validate_registry(_pages.PAGE_REGISTRY) - if callable(layout): - layout = await execute_async_function( - layout, - **{**(path_variables or {}), **query_parameters, **states}, - ) - if callable(title): - title = await execute_async_function( - title, **(path_variables or {}) - ) + if not self.config.suppress_callback_exceptions: - return layout, {"title": title} + async def get_layouts(): + return [ + await execute_async_function(page["layout"]) + if callable(page["layout"]) + else page["layout"] + for page in _pages.PAGE_REGISTRY.values() + ] - _validate.check_for_duplicate_pathnames(_pages.PAGE_REGISTRY) - _validate.validate_registry(_pages.PAGE_REGISTRY) + layouts = await get_layouts() + # pylint: disable=not-callable + layouts += [self.layout() if callable(self.layout) else self.layout] + self.validation_layout = html.Div(layouts) + if _ID_CONTENT not in self.validation_layout: + raise Exception("`dash.page_container` not found in the layout") - # Set validation_layout - if not self.config.suppress_callback_exceptions: - self.validation_layout = html.Div( - [ - asyncio.run(execute_async_function(page["layout"])) - if callable(page["layout"]) - else page["layout"] - for page in _pages.PAGE_REGISTRY.values() - ] - + [ - # pylint: disable=not-callable - self.layout() - if callable(self.layout) - else self.layout - ] - ) - if _ID_CONTENT not in self.validation_layout: - raise Exception("`dash.page_container` not found in the layout") - else: + self.clientside_callback( + """ + function(data) { + document.title = data.title + } + """, + Output(_ID_DUMMY, "children"), + Input(_ID_STORE, "data"), + hidden=True, + ) - @self.callback( - Output(_ID_CONTENT, "children"), - Output(_ID_STORE, "data"), - inputs=inputs, - prevent_initial_call=True, - hidden=True, - ) - def update(pathname_, search_, **states): - """ - Updates dash.page_container layout on page navigation. - Updates the stored page title which will trigger the clientside callback to update the app title - """ - - query_parameters = _parse_query_string(search_) - page, path_variables = _path_to_page( - self.strip_relative_path(pathname_) - ) + # Sync version + def router_sync(): + if self._got_first_request["pages"]: + return + self._got_first_request["pages"] = True - # get layout - if page == {}: - for module, page in _pages.PAGE_REGISTRY.items(): - if module.split(".")[-1] == "not_found_404": - layout = page["layout"] - title = page["title"] - break - else: - layout = html.H1("404 - Page not found") - title = self.title + inputs = { + "pathname_": Input(_ID_LOCATION, "pathname"), + "search_": Input(_ID_LOCATION, "search"), + } + inputs.update(self.routing_callback_inputs) + + @self.callback( + Output(_ID_CONTENT, "children"), + Output(_ID_STORE, "data"), + inputs=inputs, + prevent_initial_call=True, + hidden=True, + ) + def update(pathname_, search_, **states): + query_parameters = _parse_query_string(search_) + page, path_variables = _path_to_page( + self.strip_relative_path(pathname_) + ) + if page == {}: + for module, page in _pages.PAGE_REGISTRY.items(): + if module.split(".")[-1] == "not_found_404": + layout = page["layout"] + title = page["title"] + break else: - layout = page.get("layout", "") - title = page["title"] + layout = html.H1("404 - Page not found") + title = self.title + else: + layout = page.get("layout", "") + title = page["title"] - if callable(layout): - layout = layout( - **{**(path_variables or {}), **query_parameters, **states} - ) - if callable(title): - title = title(**(path_variables or {})) - - return layout, {"title": title} - - _validate.check_for_duplicate_pathnames(_pages.PAGE_REGISTRY) - _validate.validate_registry(_pages.PAGE_REGISTRY) - - # Set validation_layout - if not self.config.suppress_callback_exceptions: - layout = self.layout - if not isinstance(layout, list): - layout = [ - # pylint: disable=not-callable - self.layout() - if callable(self.layout) - else self.layout - ] - self.validation_layout = html.Div( - [ - page["layout"]() - if callable(page["layout"]) - else page["layout"] - for page in _pages.PAGE_REGISTRY.values() - ] - + layout - ) - if _ID_CONTENT not in self.validation_layout: - raise Exception("`dash.page_container` not found in the layout") + if callable(layout): + layout = layout( + **{**(path_variables or {}), **query_parameters, **states} + ) + if callable(title): + title = title(**(path_variables or {})) + return layout, {"title": title} + + _validate.check_for_duplicate_pathnames(_pages.PAGE_REGISTRY) + _validate.validate_registry(_pages.PAGE_REGISTRY) + + if not self.config.suppress_callback_exceptions: + layout = self.layout + if not isinstance(layout, list): + # pylint: disable=not-callable + layout = [self.layout() if callable(self.layout) else self.layout] + self.validation_layout = html.Div( + [ + page["layout"]() if callable(page["layout"]) else page["layout"] + for page in _pages.PAGE_REGISTRY.values() + ] + + layout + ) + if _ID_CONTENT not in self.validation_layout: + raise Exception("`dash.page_container` not found in the layout") - # Update the page title on page navigation self.clientside_callback( """ - function(data) {{ + function(data) { document.title = data.title - }} + } """, Output(_ID_DUMMY, "children"), Input(_ID_STORE, "data"), - hidden=True, ) - def __call__(self, environ, start_response): - """ - This method makes instances of Dash WSGI-compliant callables. - It delegates the actual WSGI handling to the internal Flask app's - __call__ method. - """ - return self.server(environ, start_response) + if self._use_async: + self.backend.before_request(router_async) + else: + self.backend.before_request(router_sync) + + def __call__(self, *args, **kwargs): + return self.backend.__call__(*args, **kwargs) diff --git a/dash/testing/application_runners.py b/dash/testing/application_runners.py index dc88afe844..6e6cc8b810 100644 --- a/dash/testing/application_runners.py +++ b/dash/testing/application_runners.py @@ -171,7 +171,13 @@ def run(): self.port = options["port"] try: - app.run(threaded=True, **options) + module = app.server.__class__.__module__ + # FastAPI support + if module.startswith("fastapi"): + app.run(**options) + # Dash/Flask/Quart fallback + else: + app.run(threaded=True, **options) except SystemExit: logger.info("Server stopped") except Exception as error: @@ -229,7 +235,13 @@ def target(): options = kwargs.copy() try: - app.run(threaded=True, **options) + module = app.server.__class__.__module__ + # FastAPI support + if module.startswith("fastapi"): + app.run(**options) + # Dash/Flask/Quart fallback + else: + app.run(threaded=True, **options) except SystemExit: logger.info("Server stopped") raise diff --git a/package.json b/package.json index fa4888dee7..527df37583 100644 --- a/package.json +++ b/package.json @@ -44,7 +44,7 @@ "setup-tests.R": "run-s private::test.R.deploy-*", "citest.integration": "run-s setup-tests.py private::test.integration-*", "citest.unit": "run-s private::test.unit-**", - "test": "pytest && cd dash/dash-renderer && npm run test", + "test": "pytest --ignore=tests/backend_tests && cd dash/dash-renderer && npm run test", "first-build": "cd dash/dash-renderer && npm i && cd ../../ && cd components/dash-html-components && npm i && npm run extract && cd ../../ && npm run build" }, "devDependencies": { diff --git a/quart_app.py b/quart_app.py new file mode 100644 index 0000000000..54d40add56 --- /dev/null +++ b/quart_app.py @@ -0,0 +1,23 @@ +from dash import Dash, html, Input, Output +from dash import dcc +from dash import backends + +app = Dash(__name__, backend="quart") + +app.layout = html.Div( + [ + html.H2("Quart Server Factory Example"), + html.Div("Type below to see async callback update."), + dcc.Input(id="text", value="hello", autoComplete="off"), + html.Div(id="echo"), + ] +) + + +@app.callback(Output("echo", "children"), Input("text", "value")) +def update_echo(val): + return f"You typed: {val}" if val else "Type something" + + +if __name__ == "__main__": + app.run(debug=True) diff --git a/requirements/fastapi.txt b/requirements/fastapi.txt new file mode 100644 index 0000000000..97dc7cd8c1 --- /dev/null +++ b/requirements/fastapi.txt @@ -0,0 +1,2 @@ +fastapi +uvicorn diff --git a/requirements/quart.txt b/requirements/quart.txt new file mode 100644 index 0000000000..60af440c9c --- /dev/null +++ b/requirements/quart.txt @@ -0,0 +1 @@ +quart diff --git a/setup.py b/setup.py index f87ef21d70..e2ecb16055 100644 --- a/setup.py +++ b/setup.py @@ -36,6 +36,8 @@ def read_req_file(req_type): "celery": read_req_file("celery"), "diskcache": read_req_file("diskcache"), "compress": read_req_file("compress"), + "fastapi": read_req_file("fastapi"), + "quart": read_req_file("quart"), "cloud": read_req_file("cloud"), "ag-grid": read_req_file("ag-grid") }, diff --git a/tests/backend_tests/__init__.py b/tests/backend_tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/backend_tests/test_custom_backend.py b/tests/backend_tests/test_custom_backend.py new file mode 100644 index 0000000000..befff7734b --- /dev/null +++ b/tests/backend_tests/test_custom_backend.py @@ -0,0 +1,246 @@ +import pytest +from dash import Dash, Input, Output, html, dcc +import traceback +import re + +try: + from dash.backends._fastapi import FastAPIDashServer +except ImportError: + FastAPIDashServer = None + + +class CustomDashServer(FastAPIDashServer): + def _get_traceback(self, _secret, error: Exception): + tb = error.__traceback__ + errors = traceback.format_exception(type(error), error, tb) + pass_errs = [] + callback_handled = False + for err in errors: + if self.error_handling_mode == "prune": + if not callback_handled: + if "callback invoked" in str(err) and "_callback.py" in str(err): + callback_handled = True + continue + pass_errs.append(err) + formatted_tb = "".join(pass_errs) + error_type = type(error).__name__ + error_msg = str(error) + # Parse traceback lines to group by file + file_cards = [] + pattern = re.compile(r' File "(.+)", line (\d+), in (\w+)') + lines = formatted_tb.split("\n") + current_file = None + card_lines = [] + for line in lines[:-1]: # Skip the last line (error message) + match = pattern.match(line) + if match: + if current_file and card_lines: + file_cards.append((current_file, card_lines)) + current_file = ( + f"{match.group(1)} (line {match.group(2)}, in {match.group(3)})" + ) + card_lines = [line] + elif current_file: + card_lines.append(line) + if current_file and card_lines: + file_cards.append((current_file, card_lines)) + cards_html = "" + for filename, card in file_cards: + cards_html += ( + f""" +
+
{filename}
+
"""
+                + "\n".join(card)
+                + """
+
+ """ + ) + html = f""" + + + + {error_type}: {error_msg} // Custom Debugger + + + +
+

{error_type}: {error_msg}

+ {cards_html} +
+ + + """ + return html + + +@pytest.mark.parametrize( + "fixture,input_value", + [ + ("dash_duo", "Hello CustomBackend!"), + ], +) +def test_custom_backend_basic_callback(request, fixture, input_value): + dash_duo = request.getfixturevalue(fixture) + app = Dash(__name__, backend=CustomDashServer) + app.layout = html.Div( + [dcc.Input(id="input", value=input_value, type="text"), html.Div(id="output")] + ) + + @app.callback(Output("output", "children"), Input("input", "value")) + def update_output(value): + return f"You typed: {value}" + + dash_duo.start_server(app) + dash_duo.wait_for_text_to_equal("#output", f"You typed: {input_value}") + dash_duo.clear_input(dash_duo.find_element("#input")) + dash_duo.find_element("#input").send_keys("CustomBackend Test") + dash_duo.wait_for_text_to_equal("#output", "You typed: CustomBackend Test") + assert dash_duo.get_logs() == [] + + +@pytest.mark.parametrize( + "fixture,start_server_kwargs", + [ + ("dash_duo", {"debug": True, "reload": False, "dev_tools_ui": True}), + ], +) +def test_custom_backend_error_handling(request, fixture, start_server_kwargs): + dash_duo = request.getfixturevalue(fixture) + app = Dash(__name__, backend=CustomDashServer) + app.layout = html.Div( + [html.Button(id="btn", children="Error", n_clicks=0), html.Div(id="output")] + ) + + @app.callback(Output("output", "children"), Input("btn", "n_clicks")) + def error_callback(n): + if n and n > 0: + return 1 / 0 # Intentional error + return "No error" + + dash_duo.start_server(app, **start_server_kwargs) + dash_duo.wait_for_text_to_equal("#output", "No error") + dash_duo.find_element("#btn").click() + dash_duo.wait_for_text_to_equal(dash_duo.devtools_error_count_locator, "1") + + +def get_error_html(dash_duo, index): + # error is in an iframe so is annoying to read out - get it from the store + return dash_duo.driver.execute_script( + "return store.getState().error.backEnd[{}].error.html;".format(index) + ) + + +@pytest.mark.parametrize( + "fixture,start_server_kwargs", + [ + ( + "dash_duo", + { + "debug": True, + "dev_tools_ui": True, + "dev_tools_prune_errors": False, + "reload": False, + }, + ), + ], +) +def test_custom_backend_error_handling_no_prune(request, fixture, start_server_kwargs): + dash_duo = request.getfixturevalue(fixture) + app = Dash(__name__, backend=CustomDashServer) + app.layout = html.Div( + [html.Button(id="btn", children="Error", n_clicks=0), html.Div(id="output")] + ) + + @app.callback(Output("output", "children"), Input("btn", "n_clicks")) + def error_callback(n): + if n and n > 0: + return 1 / 0 # Intentional error + return "No error" + + dash_duo.start_server(app, **start_server_kwargs) + dash_duo.wait_for_text_to_equal("#output", "No error") + dash_duo.find_element("#btn").click() + dash_duo.wait_for_text_to_equal(dash_duo.devtools_error_count_locator, "1") + + error0 = get_error_html(dash_duo, 0) + assert "Custom Debugger" in error0 + assert "in error_callback" in error0 + assert "ZeroDivisionError" in error0 + assert "_callback.py" in error0 + + +@pytest.mark.parametrize( + "fixture,start_server_kwargs, error_msg", + [ + ("dash_duo", {"debug": True, "reload": False}, "custombackend.py"), + ], +) +def test_custom_backend_error_handling_prune( + request, fixture, start_server_kwargs, error_msg +): + dash_duo = request.getfixturevalue(fixture) + app = Dash(__name__, backend=CustomDashServer) + app.layout = html.Div( + [html.Button(id="btn", children="Error", n_clicks=0), html.Div(id="output")] + ) + + @app.callback(Output("output", "children"), Input("btn", "n_clicks")) + def error_callback(n): + if n and n > 0: + return 1 / 0 # Intentional error + return "No error" + + dash_duo.start_server(app, **start_server_kwargs) + dash_duo.wait_for_text_to_equal("#output", "No error") + dash_duo.find_element("#btn").click() + dash_duo.wait_for_text_to_equal(dash_duo.devtools_error_count_locator, "1") + + error0 = get_error_html(dash_duo, 0) + assert "Custom Debugger" in error0 + assert "in error_callback" in error0 + assert "ZeroDivisionError" in error0 + assert "_callback.py" not in error0 + + +@pytest.mark.parametrize( + "fixture,input_value", + [ + ("dash_duo", "Background CustomBackend!"), + ], +) +def test_custom_backend_background_callback(request, fixture, input_value): + dash_duo = request.getfixturevalue(fixture) + import diskcache + + cache = diskcache.Cache("./cache") + from dash.background_callback import DiskcacheManager + + background_callback_manager = DiskcacheManager(cache) + + app = Dash( + __name__, + backend=CustomDashServer, + background_callback_manager=background_callback_manager, + ) + app.layout = html.Div( + [dcc.Input(id="input", value=input_value, type="text"), html.Div(id="output")] + ) + + @app.callback( + Output("output", "children"), Input("input", "value"), background=True + ) + def update_output_bg(value): + return f"Background typed: {value}" + + dash_duo.start_server(app) + dash_duo.wait_for_text_to_equal("#output", f"Background typed: {input_value}") + dash_duo.clear_input(dash_duo.find_element("#input")) + dash_duo.find_element("#input").send_keys("CustomBackend BG Test") + dash_duo.wait_for_text_to_equal( + "#output", "Background typed: CustomBackend BG Test" + ) + assert dash_duo.get_logs() == [] diff --git a/tests/backend_tests/test_preconfig_backends.py b/tests/backend_tests/test_preconfig_backends.py new file mode 100644 index 0000000000..eec832070a --- /dev/null +++ b/tests/backend_tests/test_preconfig_backends.py @@ -0,0 +1,293 @@ +import logging +import pytest +from dash import Dash, Input, Output, html, dcc, ctx + + +@pytest.mark.parametrize( + "backend,fixture", + [ + ("flask", "dash_duo"), + ("fastapi", "dash_duo"), + ("quart", "dash_duo_mp"), + ], +) +def test_set_cookie_and_header(request, backend, fixture): + dash_duo = request.getfixturevalue(fixture) + app = Dash(__name__, backend=backend) + app.layout = html.Div([html.Button("Set", id="btn"), html.Div(id="output")]) + + @app.callback(Output("output", "children"), Input("btn", "n_clicks")) + def set_cookie_and_header(n): + if ctx.response: + ctx.response.set_cookie("mycookie", "cookieval") + ctx.response.set_header("X-My-Header", "HeaderVal") + ctx.response.append_header("X-My-Header", "HeaderVal2") + ctx.response.append_header("X-My-Header2", "HeaderVal3") + ctx.response.set_header("X-My-Header2", "HeaderVal4") + return f"Clicked {n}" if n else "Not clicked" + + dash_duo.start_server(app) + dash_duo.driver.execute_script( + """ + window._lastResponseHeaders = null; + const origFetch = window.fetch; + window.fetch = async function() { + const response = await origFetch.apply(this, arguments); + response.clone().headers.forEach((v, k) => { + if (!window._lastResponseHeaders) window._lastResponseHeaders = {}; + window._lastResponseHeaders[k] = v; + }); + return response; + }; + """ + ) + + dash_duo.find_element("#btn").click() + dash_duo.wait_for_text_to_equal("#output", "Clicked 1") + + # Check cookie + cookies = dash_duo.driver.get_cookies() + assert any(c["name"] == "mycookie" and c["value"] == "cookieval" for c in cookies) + + headers = dash_duo.driver.execute_script("return window._lastResponseHeaders;") + assert headers and headers["x-my-header"] == "HeaderVal, HeaderVal2" + assert headers and headers["x-my-header2"] == "HeaderVal4" + + +@pytest.mark.parametrize( + "backend,fixture,input_value", + [ + ("fastapi", "dash_duo", "Hello FastAPI!"), + ("quart", "dash_duo_mp", "Hello Quart!"), + ], +) +def test_backend_basic_callback(request, backend, fixture, input_value): + dash_duo = request.getfixturevalue(fixture) + if backend == "fastapi": + from fastapi import FastAPI + + server = FastAPI() + else: + import quart + + server = quart.Quart(__name__) + app = Dash(__name__, server=server) + app.layout = html.Div( + [dcc.Input(id="input", value=input_value, type="text"), html.Div(id="output")] + ) + + @app.callback(Output("output", "children"), Input("input", "value")) + def update_output(value): + return f"You typed: {value}" + + dash_duo.start_server(app) + dash_duo.wait_for_text_to_equal("#output", f"You typed: {input_value}") + dash_duo.clear_input(dash_duo.find_element("#input")) + dash_duo.find_element("#input").send_keys(f"{backend.title()} Test") + dash_duo.wait_for_text_to_equal("#output", f"You typed: {backend.title()} Test") + assert dash_duo.get_logs() == [] + + +@pytest.mark.parametrize( + "backend,fixture,start_server_kwargs", + [ + ( + "fastapi", + "dash_duo", + {"debug": True, "reload": False, "dev_tools_ui": True}, + ), + ( + "quart", + "dash_duo_mp", + { + "debug": True, + "use_reloader": False, + "dev_tools_hot_reload": False, + }, + ), + ], +) +def test_backend_error_handling(request, backend, fixture, start_server_kwargs): + dash_duo = request.getfixturevalue(fixture) + app = Dash(__name__, backend=backend) + app.layout = html.Div( + [html.Button(id="btn", children="Error", n_clicks=0), html.Div(id="output")] + ) + + @app.callback(Output("output", "children"), Input("btn", "n_clicks")) + def error_callback(n): + if n and n > 0: + return 1 / 0 # Intentional error + return "No error" + + dash_duo.start_server(app, **start_server_kwargs) + dash_duo.wait_for_text_to_equal("#output", "No error") + dash_duo.find_element("#btn").click() + dash_duo.wait_for_text_to_equal(dash_duo.devtools_error_count_locator, "1") + + +def get_error_html(dash_duo, index): + # error is in an iframe so is annoying to read out - get it from the store + return dash_duo.driver.execute_script( + "return store.getState().error.backEnd[{}].error.html;".format(index) + ) + + +@pytest.mark.parametrize( + "backend,fixture,start_server_kwargs, error_msg", + [ + ( + "fastapi", + "dash_duo", + { + "debug": True, + "dev_tools_ui": True, + "dev_tools_prune_errors": False, + "reload": False, + }, + "_fastapi.py", + ), + ( + "quart", + "dash_duo_mp", + { + "debug": True, + "use_reloader": False, + "dev_tools_hot_reload": False, + "dev_tools_prune_errors": False, + }, + "_quart.py", + ), + ], +) +def test_backend_error_handling_no_prune( + request, backend, fixture, start_server_kwargs, error_msg +): + dash_duo = request.getfixturevalue(fixture) + app = Dash(__name__, backend=backend) + app.layout = html.Div( + [html.Button(id="btn", children="Error", n_clicks=0), html.Div(id="output")] + ) + + @app.callback(Output("output", "children"), Input("btn", "n_clicks")) + def error_callback(n): + if n and n > 0: + return 1 / 0 # Intentional error + return "No error" + + dash_duo.start_server(app, **start_server_kwargs) + dash_duo.wait_for_text_to_equal("#output", "No error") + dash_duo.find_element("#btn").click() + dash_duo.wait_for_text_to_equal(dash_duo.devtools_error_count_locator, "1") + + error0 = get_error_html(dash_duo, 0) + assert "in error_callback" in error0 + assert "ZeroDivisionError" in error0 + assert "backends/" in error0 and error_msg in error0 + + +@pytest.mark.parametrize( + "backend,fixture,start_server_kwargs, error_msg", + [ + ("fastapi", "dash_duo", {"debug": True, "reload": False}, "fastapi.py"), + ( + "quart", + "dash_duo_mp", + { + "debug": True, + "use_reloader": False, + "dev_tools_hot_reload": False, + }, + "quart.py", + ), + ], +) +def test_backend_error_handling_prune( + request, backend, fixture, start_server_kwargs, error_msg +): + dash_duo = request.getfixturevalue(fixture) + app = Dash(__name__, backend=backend) + app.layout = html.Div( + [html.Button(id="btn", children="Error", n_clicks=0), html.Div(id="output")] + ) + + @app.callback(Output("output", "children"), Input("btn", "n_clicks")) + def error_callback(n): + if n and n > 0: + return 1 / 0 # Intentional error + return "No error" + + dash_duo.start_server(app, **start_server_kwargs) + dash_duo.wait_for_text_to_equal("#output", "No error") + dash_duo.find_element("#btn").click() + dash_duo.wait_for_text_to_equal(dash_duo.devtools_error_count_locator, "1") + + error0 = get_error_html(dash_duo, 0) + assert "in error_callback" in error0 + assert "ZeroDivisionError" in error0 + assert "dash/backends/" not in error0 and error_msg not in error0 + + +@pytest.mark.parametrize( + "backend,fixture,input_value", + [ + ("fastapi", "dash_duo", "Background FastAPI!"), + ("quart", "dash_duo_mp", "Background Quart!"), + ], +) +def test_backend_background_callback(request, backend, fixture, input_value): + dash_duo = request.getfixturevalue(fixture) + import diskcache + + cache = diskcache.Cache("./cache") + from dash.background_callback import DiskcacheManager + + background_callback_manager = DiskcacheManager(cache) + + app = Dash( + __name__, + backend=backend, + background_callback_manager=background_callback_manager, + ) + app.layout = html.Div( + [dcc.Input(id="input", value=input_value, type="text"), html.Div(id="output")] + ) + + @app.callback( + Output("output", "children"), Input("input", "value"), background=True + ) + def update_output_bg(value): + return f"Background typed: {value}" + + dash_duo.start_server(app) + dash_duo.wait_for_text_to_equal("#output", f"Background typed: {input_value}") + dash_duo.clear_input(dash_duo.find_element("#input")) + dash_duo.find_element("#input").send_keys(f"{backend.title()} BG Test") + dash_duo.wait_for_text_to_equal( + "#output", f"Background typed: {backend.title()} BG Test" + ) + assert dash_duo.get_logs() == [] + + +@pytest.mark.parametrize( + "backend,expected_loggers", + [ + ("flask", ["werkzeug"]), + ("quart", ["hypercorn.access", "hypercorn.error"]), + ("fastapi", ["uvicorn.access", "uvicorn.error"]), + ], +) +def test_silence_routes_logging(backend, expected_loggers): + """Test that route logging is silenced for all backends when dev_tools_silence_routes_logging is enabled.""" + app = Dash(__name__, backend=backend) + app.layout = html.Div([html.Div(id="output", children="Test")]) + + # Enable dev tools with silence_routes_logging + app.enable_dev_tools(debug=True, dev_tools_silence_routes_logging=True) + + # Check that the expected loggers have been set to ERROR level + for logger_name in expected_loggers: + logger = logging.getLogger(logger_name) + assert ( + logger.level == logging.ERROR + ), f"Logger {logger_name} should be set to ERROR level for {backend} backend" diff --git a/tests/integration/devtools/test_devtools_error_handling.py b/tests/integration/devtools/test_devtools_error_handling.py index 40d5731202..005bf8c335 100644 --- a/tests/integration/devtools/test_devtools_error_handling.py +++ b/tests/integration/devtools/test_devtools_error_handling.py @@ -109,14 +109,14 @@ def test_dveh006_long_python_errors(dash_duo): assert "in bad_sub" not in error0 # dash and flask part of the traceback ARE included # since we set dev_tools_prune_errors=False - assert "dash.py" in error0 + assert "backend" in error0 and "flask.py" in error0 assert "self.wsgi_app" in error0 error1 = get_error_html(dash_duo, 1) assert "in update_output" in error1 assert "in bad_sub" in error1 assert "ZeroDivisionError" in error1 - assert "dash.py" in error1 + assert "backend" in error1 and "flask.py" in error1 assert "self.wsgi_app" in error1 diff --git a/tests/integration/multi_page/test_pages_layout.py b/tests/integration/multi_page/test_pages_layout.py index 48751021b9..a209ae4517 100644 --- a/tests/integration/multi_page/test_pages_layout.py +++ b/tests/integration/multi_page/test_pages_layout.py @@ -3,6 +3,7 @@ from dash import Dash, Input, State, dcc, html, Output from dash.dash import _ID_LOCATION from dash.exceptions import NoLayoutException +from dash.testing.wait import until def get_app(path1="/", path2="/layout2"): @@ -57,7 +58,7 @@ def test_pala001_layout(dash_duo, clear_pages_state): for page in dash.page_registry.values(): dash_duo.find_element("#" + page["id"]).click() dash_duo.wait_for_text_to_equal("#text_" + page["id"], "text for " + page["id"]) - assert dash_duo.driver.title == page["title"], "check that page title updates" + until(lambda: dash_duo.driver.title == page["title"], timeout=3) # test redirects dash_duo.wait_for_page(url=f"{dash_duo.server_url}/v2") diff --git a/tests/integration/multi_page/test_pages_relative_path.py b/tests/integration/multi_page/test_pages_relative_path.py index 6c505ac3f5..24e7209a70 100644 --- a/tests/integration/multi_page/test_pages_relative_path.py +++ b/tests/integration/multi_page/test_pages_relative_path.py @@ -2,6 +2,7 @@ import dash from dash import Dash, dcc, html +from dash.testing.wait import until def get_app(app): @@ -70,7 +71,7 @@ def test_pare002_relative_path_with_url_base_pathname( for page in dash.page_registry.values(): dash_br.find_element("#" + page["id"]).click() dash_br.wait_for_text_to_equal("#text_" + page["id"], "text for " + page["id"]) - assert dash_br.driver.title == page["title"], "check that page title updates" + until(lambda: dash_br.driver.title == page["title"], timeout=3) assert dash_br.get_logs() == [], "browser console should contain no error" @@ -83,6 +84,6 @@ def test_pare003_absolute_path(dash_duo, clear_pages_state): for page in dash.page_registry.values(): dash_duo.find_element("#" + page["id"]).click() dash_duo.wait_for_text_to_equal("#text_" + page["id"], "text for " + page["id"]) - assert dash_duo.driver.title == page["title"], "check that page title updates" + until(lambda: dash_duo.driver.title == page["title"], timeout=3) assert dash_duo.get_logs() == [], "browser console should contain no error"