Learn R Programming

dash (version 0.9.4)

Dash: R6 class representing a Dash application

Description

A framework for building analytical web applications, Dash offers a pleasant and productive development experience. No JavaScript required.

Arguments

Format

An R6::R6Class generator object

Public fields

server

A cloned (and modified) version of the fiery::Fire object provided to the server argument (various routes will be added which enable Dash functionality).

config

A list of configuration options passed along to dash-renderer. Users shouldn't need to alter any of these options unless they are constructing their own authorization front-end or otherwise need to know where the application is making API calls.

Methods

Public methods

Method new()

Create and configure a Dash application.

Usage

Dash$new(
  server = fiery::Fire$new(),
  assets_folder = "assets",
  assets_url_path = "/assets",
  eager_loading = FALSE,
  assets_ignore = "",
  serve_locally = TRUE,
  meta_tags = NULL,
  url_base_pathname = "/",
  routes_pathname_prefix = NULL,
  requests_pathname_prefix = NULL,
  external_scripts = NULL,
  external_stylesheets = NULL,
  compress = TRUE,
  suppress_callback_exceptions = FALSE,
  show_undo_redo = FALSE,
  update_title = "Updating..."
)

Arguments

server

fiery::Fire object. The web server used to power the application.

assets_folder

Character. A path, relative to the current working directory, for extra files to be used in the browser. All .js and .css files will be loaded immediately unless excluded by assets_ignore, and other files such as images will be served if requested. Default is assets.

assets_url_path

Character. Specify the URL path for asset serving. Default is assets.

eager_loading

Logical. Controls whether asynchronous resources are prefetched (if TRUE) or loaded on-demand (if FALSE).

assets_ignore

Character. A regular expression, to match assets to omit from immediate loading. Ignored files will still be served if specifically requested. You cannot use this to prevent access to sensitive files.

serve_locally

Logical. Whether to serve HTML dependencies locally or remotely (via URL).

meta_tags

List of lists. HTML <meta> tags to be added to the index page. Each list element should have the attributes and values for one tag, eg: list(name = 'description', content = 'My App').

url_base_pathname

Character. A local URL prefix to use app-wide. Default is /. Both requests_pathname_prefix and routes_pathname_prefix default to url_base_pathname. Environment variable is DASH_URL_BASE_PATHNAME.

routes_pathname_prefix

Character. A prefix applied to the backend routes. Environment variable is DASH_ROUTES_PATHNAME_PREFIX.

requests_pathname_prefix

Character. A prefix applied to request endpoints made by Dash's front-end. Environment variable is DASH_REQUESTS_PATHNAME_PREFIX.

external_scripts

List. An optional list of valid URLs from which to serve JavaScript source for rendered pages. Each entry can be a string (the URL) or a named list with src (the URL) and optionally other <script> tag attributes such as integrity and crossorigin.

external_stylesheets

List. An optional list of valid URLs from which to serve CSS for rendered pages. Each entry can be a string (the URL) or a list with href (the URL) and optionally other <link> tag attributes such as rel, integrity and crossorigin.

compress

Logical. Whether to try to compress files and data served by Fiery. By default, brotli is attempted first, then gzip, then the deflate algorithm, before falling back to identity.

suppress_callback_exceptions

Logical. Whether to relay warnings about possible layout mis-specifications when registering a callback.

show_undo_redo

Logical. Set to TRUE to enable undo and redo buttons for stepping through the history of the app state.

update_title

Character. Defaults to Updating...; configures the document.title (the text that appears in a browser tab) text when a callback is being run. Set to NULL or '' if you don't want the document.title to change or if you want to control the document.title through a separate component or clientside callback.

Method server_route()

Connect a URL to a custom server route

Usage

Dash$server_route(path = NULL, handler = NULL, methods = "get")

Arguments

path

Character. Represents a URL path comprised of strings, parameters (strings prefixed with :), and wildcards (*), separated by /. Wildcards can be used to match any path element, rather than restricting (as by default) to a single path element. For example, it is possible to catch requests to multiple subpaths using a wildcard. For more information, see Route.

handler

Function. Adds a handler function to the specified method and path. For more information, see Route.

methods

Character. A string indicating the request method (in lower case, e.g. 'get', 'put', etc.), as used by reqres. The default is get. For more information, see Route.

Details

fiery, the underlying web service framework upon which Dash for R is based, supports custom routing through plugins. While convenient, the plugin API providing this functionality is different from that provided by Flask, as used by Dash for Python. This method wraps the pluggable routing of routr routes in a manner that should feel slightly more idiomatic to Dash users.

Querying User-Defined Routes:

It is possible to retrieve the list of user-defined routes by invoking the get_data method. For example, if your Dash application object is app, use app$server$get_data("user-routes").

If you wish to erase all user-defined routes without instantiating a new Dash application object, one option is to clear the routes manually: app$server$set_data("user-routes", list()).

Examples

library(dash)
app <- Dash$new()

# A handler to redirect requests with `307` status code (temporary redirects); # for permanent redirects (`301`), see the `redirect` method described below # # A simple single path-to-path redirect app$server_route('/getting-started', function(request, response, keys, ...) { response$status <- 307L response$set_header('Location', '/layout') TRUE })

# Example of a redirect with a wildcard for subpaths app$server_route('/getting-started/*', function(request, response, keys, ...) { response$status <- 307L response$set_header('Location', '/layout') TRUE })

# Example of a parameterized redirect with wildcard for subpaths app$server_route('/accounts/:user_id/*', function(request, response, keys, ...) { response$status <- 307L response$set_header('Location', paste0('/users/', keys$user_id)) TRUE })

Method redirect()

Redirect a Dash application URL path

Usage

Dash$redirect(old_path = NULL, new_path = NULL, methods = "get")

Arguments

old_path

Character. Represents the URL path to redirect, comprised of strings, parameters (strings prefixed with :), and wildcards (*), separated by /. Wildcards can be used to match any path element, rather than restricting (as by default) to a single path element. For example, it is possible to catch requests to multiple subpaths using a wildcard. For more information, see Route.

new_path

Character or function. Same as old_path, but represents the new path which the client should load instead. If a function is provided instead of a string, it should have keys within its formals.

methods

Character. A string indicating the request method (in lower case, e.g. 'get', 'put', etc.), as used by reqres. The default is get. For more information, see Route.

Details

This is a convenience method to simplify adding redirects for your Dash application which automatically return a 301 HTTP status code and direct the client to load an alternate URL.

Examples

library(dash)
app <- Dash$new()

# example of a simple single path-to-path redirect app$redirect("/getting-started", "/layout")

# example of a redirect using wildcards app$redirect("/getting-started/*", "/layout/*")

# example of a parameterized redirect using a function for new_path, # which requires passing in keys to take advantage of subpaths within # old_path that are preceded by a colon (e.g. :user_id): app$redirect("/accounts/:user_id/*", function(keys) paste0("/users/", keys$user_id))

Method layout_get()

Retrieves the Dash application layout.

Usage

Dash$layout_get(render = TRUE)

Arguments

render

Logical. If the layout is a function, should the function be executed to return the layout? If FALSE, the function is returned as-is.

Details

If render is TRUE, and the layout is a function, the result of the function (rather than the function itself) is returned.

Returns

List or function, depending on the value of render (see above). When returning an object of class dash_component, the default print method for this class will display the corresponding pretty-printed JSON representation of the object to the console.

Method layout()

Set the Dash application layout (i.e., specify its user interface).

Usage

Dash$layout(value)

Arguments

value

An object of the dash_component class, which provides a component or collection of components, specified either as a Dash component or a function that returns a Dash component.

Details

value should be either a collection of Dash components (e.g., dccSlider, htmlDiv, etc) or a function which returns a collection of components. The collection of components must be nested, such that any additional components contained within value are passed solely as children of the top-level component. In all cases, value must be a member of the dash_component class.

Method react_version_set()

Update the version of React in the list of dependencies served by dash-renderer to the client.

Usage

Dash$react_version_set(version)

Arguments

version

Character. The version number of React to use.

Method callback()

Define a Dash callback.

Usage

Dash$callback(output, params, func)

Arguments

output

Named list. The output argument provides the component id and property which will be updated by the callback; a callback can target one or more outputs (i.e. multiple outputs).

params

Unnamed list; provides input and state statements, each with its own defined id and property. For pattern-matching callbacks, the id field of a component is written in JSON-like syntax and provides fields that are arbitrary keys which describe the targets of the callback. See selectors for more details.

func

Function; must return output provided input or state arguments. func may be any valid R function, or a character string containing valid JavaScript, or a call to clientsideFunction, including namespace and function_name arguments for a locally served JavaScript function.

Details

Describes a server or clientside callback relating the values of one or more output items to one or more input items which will trigger the callback when they change, and optionally state items which provide additional information but do not trigger the callback directly.

For detailed examples of how to use pattern-matching callbacks, see the entry for selectors or visit our interactive online documentation at https://dash.plotly.com/r/.

The output argument defines which layout component property should receive the results (via the output object). The events that trigger the callback are then described by the input (and/or state) object(s) (which should reference layout components), which become argument values for R callback handlers defined in func.

Here func may either be an anonymous R function, a JavaScript function provided as a character string, or a call to clientsideFunction(), which describes a locally served JavaScript function instead. The latter two methods define a "clientside callback", which updates components without passing data to and from the Dash backend. The latter may offer improved performance relative to callbacks written purely in R.

Method callback_context()

Request and return the calling context of a Dash callback.

Usage

Dash$callback_context()

Details

The callback_context method permits retrieving the inputs which triggered the firing of a given callback, and allows introspection of the input/state values given their names. It is only available from within a callback; attempting to use this method outside of a callback will result in a warning.

The callback_context method returns a list containing three elements: states, triggered, inputs. The first and last of these correspond to the values of states and inputs for the current invocation of the callback, and triggered provides a list of changed properties.

Returns

List comprising elements states, triggered, inputs.

Method callback_context.record_timing()

Records timing information for a server resource.

Usage

Dash$callback_context.record_timing(name, duration = NULL, description = NULL)

Arguments

name

Character. The name of the resource.

duration

Numeric. The time in seconds to report. Internally, this is rounded to the nearest millisecond.

description

Character. A description of the resource.

Details

The callback_context.record_timing method permits retrieving the duration required to execute a given callback. It may only be called from within a callback; a warning will be thrown and the method will otherwise return NULL if invoked outside of a callback.

Method get_asset_url()

Return a URL for a Dash asset.

Usage

Dash$get_asset_url(asset_path, prefix = self$config$requests_pathname_prefix)

Arguments

asset_path

Character. Specifies asset filename whose URL should be returned.

prefix

Character. Specifies pathname prefix; default is to use requests_pathname_prefix.

Details

The get_asset_url method permits retrieval of an asset's URL given its filename. For example, app$get_asset_url('style.css') should return /assets/style.css when assets_folder = 'assets'. By default, the prefix is the value of requests_pathname_prefix, but this is configurable via the prefix parameter. Note: this method will present a warning and return NULL if the Dash app was not loaded via source() if the DASH_APP_PATH environment variable is undefined.

Returns

Character. A string representing the URL to the asset.

Method get_relative_path()

Return relative asset paths for Dash assets.

Usage

Dash$get_relative_path(
  path,
  requests_pathname_prefix = self$config$requests_pathname_prefix
)

Arguments

path

Character. A path string prefixed with a leading / which directs at a path or asset directory.

requests_pathname_prefix

Character. The pathname prefix for the application when deployed. Defaults to the environment variable set by the server, or "" if run locally.

Details

The get_relative_path method simplifies the handling of URLs and pathnames for apps running locally and on a deployment server such as Dash Enterprise. It handles the prefix for requesting assets similar to the get_asset_url method, but can also be used for URL handling in components such as dccLink or dccLocation. For example, app$get_relative_url("/page/") would return /app/page/ for an app running on a deployment server. The path must be prefixed with a /.

Returns

Character. A string describing a relative path to a Dash app's asset given a path and requests_pathname_prefix.

Method strip_relative_path()

Return a Dash asset path without its prefix.

Usage

Dash$strip_relative_path(
  path,
  requests_pathname_prefix = self$config$requests_pathname_prefix
)

Arguments

path

Character. A path string prefixed with a leading / which directs at a path or asset directory.

requests_pathname_prefix

Character. The pathname prefix for the app on a deployed application. Defaults to the environment variable set by the server, or "" if run locally.

Details

The strip_relative_path method simplifies the handling of URLs and pathnames for apps running locally and on a deployment server such as Dash Enterprise. It acts almost opposite to the get_relative_path method, by taking a relative path as an input, and returning the path stripped of the requests_pathname_prefix, and any leading or trailing /. For example, a path string /app/homepage/, would be returned as homepage. This is particularly useful for dccLocation URL routing.

Method index_string()

Specify a custom index string for a Dash application.

Usage

Dash$index_string(string)

Arguments

string

Character; the index string template, with interpolation keys included.

Details

The index_string method allows the specification of a custom index by changing the default HTML template that is generated by the Dash UI. #' Meta tags, CSS, and JavaScript are some examples of features that can be modified. This method will present a warning if your HTML template is missing any necessary elements and return an error if a valid index is not defined. The following interpolation keys are currently supported:

{%metas%}

Optional - The registered meta tags.

{%favicon%}

Optional - A favicon link tag if found in assets.

{%css%}

Optional - Link tags to CSS resources.

{%config%}

Required - Configuration details generated by Dash for the renderer.

{%app_entry%}

Required - The container where Dash React components are rendered.

{%scripts%}

Required - Script tags for collected dependencies.

Example of a basic HTML index string:

"<!DOCTYPE html>
<html>
 <head>
  {%meta_tags%}
     <title>{{
     {%favicon%}
     {%css_tags%}
 </head>
  <body>
    {%app_entry%}
    <footer>
     {%config%}
     {%scripts%}
    </footer>
  </body>
</html>"
      

Method interpolate_index()

Modify index template variables for a Dash application.

Usage

Dash$interpolate_index(template_index = private$template_index[[1]], ...)

Arguments

template_index

Character. A formatted string with the HTML index string. Defaults to the initial template.

...

Named list. The unnamed arguments can be passed as individual named lists corresponding to the components of the Dash HTML index. These include the same argument as those found in the index_string() template.

Details

With the interpolate_index method, one can pass a custom index with template string variables that are already evaluated. Directly passing arguments to the template_index has the effect of assigning them to variables present in the template. This is similar to the index_string method but offers the ability to change the default components of the Dash index as seen in the example below.

Examples

library(dash)
app <- Dash$new()

sample_template <- "<!DOCTYPE html> <html> <head> {%meta_tags%} <title>Index Template Test</title> {%favicon%} {%css_tags%} </head> <body> {%app_entry%} <footer> {%config%} {%scripts%} </footer> </body> </html>"

# this is the default configuration, but custom configurations # are possible -- the structure of the "config" argument is # a list, in which each element is a JSON key/value pair, when # reformatted as JSON from the list: # e.g. {"routes_pathname_prefix":"/", "ui":false} config <- sprintf("<script id='_dash-config' type='application/json'> %s </script>", jsonlite::toJSON(app$config, auto_unbox=TRUE))

app$interpolate_index( sample_template, metas = "<meta_charset='UTF-8'/>", app_entry = "<div id='react-entry-point'><div class='_dash-loading'>Loading...</div></div>", config = config, scripts = "")

Method title()

Set the title of the Dash app

Usage

Dash$title(string = "Dash")

Arguments

string

Character. A string representation of the name of the Dash application.

Details

If no title is supplied, Dash for R will use 'Dash'.

Method run_server()

Start the Fiery HTTP server and run a Dash application.

Usage

Dash$run_server(
  host = Sys.getenv("HOST", "127.0.0.1"),
  port = Sys.getenv("PORT", 8050),
  block = TRUE,
  showcase = FALSE,
  use_viewer = FALSE,
  dev_tools_prune_errors = TRUE,
  debug = Sys.getenv("DASH_DEBUG"),
  dev_tools_ui = Sys.getenv("DASH_UI"),
  dev_tools_props_check = Sys.getenv("DASH_PROPS_CHECK"),
  dev_tools_hot_reload = Sys.getenv("DASH_HOT_RELOAD"),
  dev_tools_hot_reload_interval = Sys.getenv("DASH_HOT_RELOAD_INTERVAL"),
  dev_tools_hot_reload_watch_interval = Sys.getenv("DASH_HOT_RELOAD_WATCH_INTERVAL)"),
  dev_tools_hot_reload_max_retry = Sys.getenv("DASH_HOT_RELOAD_MAX_RETRY"),
  dev_tools_silence_routes_logging = NULL,
  ...
)

Arguments

host

Character. A string specifying a valid IPv4 address for the Fiery server, or 0.0.0.0 to listen on all addresses. Default is 127.0.0.1 Environment variable: HOST.

port

Integer. Specifies the port number on which the server should listen (default is 8050). Environment variable: PORT.

block

Logical. Start the server while blocking console input? Default is TRUE.

showcase

Logical. Load the Dash application into the default web browser when server starts? Default is FALSE.

use_viewer

Logical. Load the Dash application into RStudio's viewer pane? Requires that host is either 127.0.0.1 or localhost, and that Dash application is started within RStudio; if use_viewer = TRUE and these conditions are not satisfied, the user is warned and the app opens in the default browser instead. Default is FALSE.

dev_tools_prune_errors

Logical. Reduce tracebacks such that only lines relevant to user code remain, stripping out Fiery and Dash references? Only available with debugging. TRUE by default, set to FALSE to see the complete traceback. Environment variable: DASH_PRUNE_ERRORS.

debug

Logical. Enable/disable all the Dash developer tools (and the within-browser user interface for the callback graph visualizer and stack traces) unless overridden by the arguments or environment variables. Default is FALSE when called via run_server. For more information, please visit https://dash.plotly.com/r/devtools. Environment variable: DASH_DEBUG.

dev_tools_ui

Logical. Show Dash's developer tools UI? Default is TRUE if debug == TRUE, FALSE otherwise. Environment variable: DASH_UI.

dev_tools_props_check

Logical. Validate the types and values of Dash component properties? Default is TRUE if debug == TRUE, FALSE otherwise. Environment variable: DASH_PROPS_CHECK.

dev_tools_hot_reload

Logical. Activate hot reloading when app, assets, and component files change? Default is TRUE if debug == TRUE, FALSE otherwise. Requires that the Dash application is loaded using source(), so that srcref attributes are available for executed code. Environment variable: DASH_HOT_RELOAD.

dev_tools_hot_reload_interval

Numeric. Interval in seconds for the client to request the reload hash. Default is 3. Environment variable: DASH_HOT_RELOAD_INTERVAL.

dev_tools_hot_reload_watch_interval

Numeric. Interval in seconds for the server to check asset and component folders for changes. Default 0.5. Environment variable: DASH_HOT_RELOAD_WATCH_INTERVAL.

dev_tools_hot_reload_max_retry

Integer. Maximum number of failed reload hash requests before failing and displaying a pop up. Default 0.5. Environment variable: DASH_HOT_RELOAD_MAX_RETRY.

dev_tools_silence_routes_logging

Logical. Replace Fiery's default logger with dashLogger instead (will remove all routes logging)? Enabled with debugging by default because hot reload hash checks generate a lot of requests.

...

Additional arguments to pass to the start handler; see the fiery documentation for relevant examples.

Details

Starts the Fiery server in local mode and launches the Dash application. If a parameter can be set by an environment variable, that is listed too. Values provided here take precedence over environment variables. . If provided, host/port set the host/port fields of the underlying fiery::Fire web server. The block/showcase/... arguments are passed along to the ignite() method of the fiery::Fire server.

Examples

if (interactive() ) {
  library(dash)

app <- Dash$new() app$layout(htmlDiv( list( dccInput(id = "inputID", value = "initial value", type = "text"), htmlDiv(id = "outputID") ) ) )

app$callback(output = list(id="outputID", property="children"), params = list(input(id="inputID", property="value"), state(id="inputID", property="type")), function(x, y) sprintf("You've entered: '%s' into a '%s' input control", x, y) )

app$run_server(showcase = TRUE) }

Method clone()

The objects of this class are cloneable with this method.

Usage

Dash$clone(deep = FALSE)

Arguments

deep

Whether to make a deep clone.

Examples

Run this code
# NOT RUN {
## ------------------------------------------------
## Method `Dash$server_route`
## ------------------------------------------------

library(dash)
app <- Dash$new()

# A handler to redirect requests with `307` status code (temporary redirects);
# for permanent redirects (`301`), see the `redirect` method described below
#
# A simple single path-to-path redirect
app$server_route('/getting-started', function(request, response, keys, ...) {
  response$status <- 307L
  response$set_header('Location', '/layout')
  TRUE
})

# Example of a redirect with a wildcard for subpaths
app$server_route('/getting-started/*', function(request, response, keys, ...) {
  response$status <- 307L
  response$set_header('Location', '/layout')
  TRUE
})

# Example of a parameterized redirect with wildcard for subpaths
app$server_route('/accounts/:user_id/*', function(request, response, keys, ...) {
  response$status <- 307L
  response$set_header('Location', paste0('/users/', keys$user_id))
  TRUE
})

## ------------------------------------------------
## Method `Dash$redirect`
## ------------------------------------------------

library(dash)
app <- Dash$new()

# example of a simple single path-to-path redirect
app$redirect("/getting-started", "/layout")

# example of a redirect using wildcards
app$redirect("/getting-started/*", "/layout/*")

# example of a parameterized redirect using a function for new_path,
# which requires passing in keys to take advantage of subpaths within
# old_path that are preceded by a colon (e.g. :user_id):
app$redirect("/accounts/:user_id/*", function(keys) paste0("/users/", keys$user_id))

## ------------------------------------------------
## Method `Dash$interpolate_index`
## ------------------------------------------------

library(dash)
app <- Dash$new()

sample_template <- "<!DOCTYPE html>
<html>
<head>
{%meta_tags%}
<title>Index Template Test</title>
{%favicon%}
{%css_tags%}
</head>
<body>
{%app_entry%}
<footer>
{%config%}
{%scripts%}
</footer>
</body>
</html>"

# this is the default configuration, but custom configurations
# are possible -- the structure of the "config" argument is
# a list, in which each element is a JSON key/value pair, when
# reformatted as JSON from the list:
#  e.g. {"routes_pathname_prefix":"/", "ui":false}
config <- sprintf("<script id='_dash-config' type='application/json'> %s </script>",
                 jsonlite::toJSON(app$config, auto_unbox=TRUE))

app$interpolate_index(
  sample_template,
  metas = "<meta_charset='UTF-8'/>",
  app_entry = "<div id='react-entry-point'><div class='_dash-loading'>Loading...</div></div>",
  config = config,
  scripts = "")

## ------------------------------------------------
## Method `Dash$run_server`
## ------------------------------------------------

if (interactive() ) {
  library(dash)

  app <- Dash$new()
  app$layout(htmlDiv(
    list(
      dccInput(id = "inputID", value = "initial value", type = "text"),
      htmlDiv(id = "outputID")
    )
   )
  )

  app$callback(output = list(id="outputID", property="children"),
               params = list(input(id="inputID", property="value"),
                        state(id="inputID", property="type")),
    function(x, y)
      sprintf("You've entered: '%s' into a '%s' input control", x, y)
  )

  app$run_server(showcase = TRUE)
}
# }

Run the code above in your browser using DataLab