Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
96 commits
Select commit Hold shift + click to select a range
49d8c21
Update layout on server with each callback, for ids in initial layout.
rmarren1 Aug 15, 2018
12dc611
Update layout for dynamically created elements with ids.
rmarren1 Aug 15, 2018
a0e2f4f
Cerberus validation of initial layout.
rmarren1 Aug 16, 2018
7eb0dbd
Recursive schema generation, schema test case.
rmarren1 Aug 18, 2018
a3ccd76
Custom validation
rmarren1 Aug 23, 2018
377ec7b
Fix validation import
rmarren1 Aug 23, 2018
ce2a255
Merge branch 'master' into validate
rmarren1 Aug 26, 2018
9d0fa01
Make test cases pass
rmarren1 Aug 26, 2018
5665fa4
Fix pylint errors
rmarren1 Aug 26, 2018
f88b068
iteritems -> items for python3 compatibility.
rmarren1 Aug 26, 2018
6205742
Fix unicode and ordering issues with oyaml.
rmarren1 Aug 27, 2018
6b65a67
use dash-renderer version with namespace and type
rmarren1 Aug 27, 2018
4df2bb8
Only validate if 'namespace' and 'type' in json body.
rmarren1 Aug 27, 2018
9e5aa93
Change loader back to json, add hook to transform unicode to string.
rmarren1 Aug 28, 2018
b045753
Do not try to match schema string exactly.
rmarren1 Aug 28, 2018
89d7137
Component validation test cases
rmarren1 Aug 29, 2018
ffd63ba
Required prop type test case
rmarren1 Aug 29, 2018
954aae3
Pylint fixes
rmarren1 Aug 29, 2018
93d4bf6
Fix dict
rmarren1 Aug 29, 2018
a934c26
Improve error message, custom exceptions.
rmarren1 Aug 29, 2018
4bb97ef
Figure validation
rmarren1 Aug 30, 2018
4cb76fe
Fix import order for Pylint.
rmarren1 Aug 30, 2018
233c145
Extra newlines in exceptions for Pylint.
rmarren1 Aug 30, 2018
cf47627
Rename exceptions import for Pylint.
rmarren1 Aug 30, 2018
2817398
Only validate against callback property.
rmarren1 Aug 30, 2018
ee3d1ab
Allow 'None' in children lists.
rmarren1 Aug 30, 2018
9240436
If prop doesn't exist in schema, don't validate callback (for wildcards)
rmarren1 Aug 30, 2018
1373fc2
Fix tests.
rmarren1 Aug 30, 2018
7e804d0
Fix Pylint.
rmarren1 Aug 30, 2018
bc947e6
Add Plotly Figure validation correctly, print error from Plotly.py
rmarren1 Aug 30, 2018
c9b693b
Update renderer requirement
rmarren1 Aug 30, 2018
6c37980
Workaround for PropTypes.null
rmarren1 Sep 2, 2018
fa74afd
Allow 'None' in children arrays.
rmarren1 Sep 3, 2018
5bcec21
Merge branch 'master' into validate
rmarren1 Sep 3, 2018
dd13a80
Fix test cases
rmarren1 Sep 3, 2018
0a33769
Bump dash-html-components version to version published from 3.7.
rmarren1 Sep 5, 2018
c42c3d5
Update integration tests.
rmarren1 Sep 5, 2018
19910ad
Try not installing virtualenv
rmarren1 Sep 6, 2018
4b02ddb
Try venv in home directory
rmarren1 Sep 6, 2018
fcbebd9
Update plotly figure validator.
rmarren1 Sep 7, 2018
54558fe
Bump version and fix pylint
rmarren1 Sep 7, 2018
603aac2
Bump core component versions.
rmarren1 Sep 7, 2018
f6ecaa7
'{}' is not a valid figure.
rmarren1 Sep 7, 2018
5d7625a
Fix figure validator and bump dash-core-components version.
rmarren1 Sep 7, 2018
357ee94
Update wildcard callback test.
rmarren1 Sep 7, 2018
f067f91
Merge branch 'master' into validate
rmarren1 Sep 7, 2018
9b5b9f2
Add Cerberus to dev requirements files
rmarren1 Sep 7, 2018
f6c15da
Allow for required `children`.
rmarren1 Sep 20, 2018
f99490f
Pylint fixes
rmarren1 Sep 21, 2018
886c83a
Merge branch 'master' into validate
rmarren1 Sep 21, 2018
e75d6f1
Fix circle
rmarren1 Sep 21, 2018
8d1727e
Ignore too-many-lines
rmarren1 Sep 21, 2018
87db60a
disable too many lines in .pylintrc
rmarren1 Sep 21, 2018
6967dad
too many lines in .pylint37 too
rmarren1 Sep 21, 2018
42fab98
Add tests for numpy ndarray / pandas series as list.
rmarren1 Sep 28, 2018
06682d2
Update list validator to work for pd.Series, np.ndarray
rmarren1 Sep 28, 2018
906e7c9
Add tests for int / float in enum.
rmarren1 Sep 28, 2018
03a7c08
Update enum to work with int / float
rmarren1 Sep 28, 2018
b1d1337
Add tests for numpy int / float
rmarren1 Sep 28, 2018
426e4f3
Update number validation to support numpy int / float
rmarren1 Sep 28, 2018
b0b5385
Change name `_validate_callback` -> `_validate_callback_definition`
rmarren1 Oct 1, 2018
d98a1a7
`_validate_callback_output` -> `_validate_callback_serialization_error`
rmarren1 Oct 1, 2018
0523beb
Add initial layout validation test.
rmarren1 Oct 1, 2018
b5b7935
Move validation to method in base component.
rmarren1 Oct 1, 2018
d8eb35f
Add disable_component_validation config option.
rmarren1 Oct 1, 2018
b8e2c67
Run component validation on initial layout.
rmarren1 Oct 1, 2018
0fd11b7
Update initial layout validation test.
rmarren1 Oct 1, 2018
2049dfb
Add callback output validation test.
rmarren1 Oct 2, 2018
a3d1402
Bump dash-html-component version in dev.
rmarren1 Oct 2, 2018
015674e
Move component validation to its own method.
rmarren1 Oct 2, 2018
8c2d97f
Move initial layout test, add initialization in callback test
rmarren1 Oct 2, 2018
9fcfa96
Change name of initialization validation error
rmarren1 Oct 2, 2018
95f20cd
Add callback component initialization validation
rmarren1 Oct 2, 2018
f92812b
Make sure children is component before validation.
rmarren1 Oct 2, 2018
0a57cc5
Add Cerberus to setup.py install_requires.
rmarren1 Oct 5, 2018
64b4f5c
Give more information in validation error messages.
rmarren1 Oct 5, 2018
0a515d2
` -> * for error message blocks, so you can copy paste to github.
rmarren1 Oct 5, 2018
dce6a06
Rebase
rmarren1 Oct 18, 2018
708c2f7
Un-comment broken test.
rmarren1 Oct 18, 2018
c8f2953
Add test for using boolean in enum
rmarren1 Oct 18, 2018
c64bc6d
Update Table test component for boolean enum values
rmarren1 Oct 18, 2018
8202256
Forgot to add changed metadata_test.py file (Table component)
rmarren1 Oct 18, 2018
e3aa8d9
Add support for boolean in enum to schema generation.
rmarren1 Oct 18, 2018
f9db291
Add a test for 'options_with_unique_values' validator.
rmarren1 Oct 19, 2018
41d0e81
Add 'options_with_unique_values' validator.
rmarren1 Oct 19, 2018
616583a
lines too long fixes.
rmarren1 Oct 19, 2018
588ce3d
pylint fixes
rmarren1 Oct 19, 2018
cead8e7
Rebase
rmarren1 Nov 2, 2018
9962b2a
Change `disable_component_validation` to `suppress_validation_callbacks`
rmarren1 Nov 2, 2018
3bcfefb
Small typo in test react component
rmarren1 Nov 2, 2018
a5093a0
Monkey patch schemas onto dash_html_components for test
rmarren1 Nov 2, 2018
4af81bf
Use sys.modules rather than dynamic import.
rmarren1 Nov 2, 2018
d81fadb
Disable validation exceptions when in production.
rmarren1 Nov 2, 2018
944bcc3
Tell user how to turn off validation exceptions in the message.
rmarren1 Nov 2, 2018
b785e1b
Pylint fixes
rmarren1 Nov 2, 2018
ea5cf00
Fix line too long
rmarren1 Nov 2, 2018
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .circleci/config.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -49,6 +49,7 @@ jobs:
python --version
python -m unittest tests.development.test_base_component
python -m unittest tests.development.test_component_loader
python -m unittest tests.development.test_component_validation
python -m unittest tests.test_integration
python -m unittest tests.test_resources
python -m unittest tests.test_configs
Expand Down
3 changes: 3 additions & 0 deletions .circleci/requirements/dev-requirements-py37.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,8 +9,11 @@ mock
tox
tox-pyenv
six
numpy
pandas
plotly>=2.0.8
requests[security]
flake8
pylint==2.1.1
astroid==2.0.4
Cerberus==1.2
3 changes: 3 additions & 0 deletions .circleci/requirements/dev-requirements.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,7 +10,10 @@ tox
tox-pyenv
mock
six
numpy
pandas
plotly>=2.0.8
requests[security]
flake8
pylint==1.9.2
Cerberus==1.2
1 change: 1 addition & 0 deletions .pylintrc37
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,6 +63,7 @@ confidence=
disable=invalid-name,
missing-docstring,
print-statement,
too-many-lines,
parameter-unpacking,
unpacking-in-except,
old-raise-syntax,
Expand Down
121 changes: 111 additions & 10 deletions dash/dash.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,11 +5,13 @@
import collections
import importlib
import json
import pprint
import pkgutil
import warnings
import re

from functools import wraps
from textwrap import dedent

import plotly
import dash_renderer
Expand All@@ -20,6 +22,8 @@
from .dependencies import Event, Input, Output, State
from .resources import Scripts, Css
from .development.base_component import Component
from .development.validator import (DashValidator,
generate_validation_error_message)
from . import exceptions
from ._utils import AttributeDict as _AttributeDict
from ._utils import interpolate_str as _interpolate
Expand DownExpand Up@@ -84,6 +88,7 @@ def __init__(
external_scripts=None,
external_stylesheets=None,
suppress_callback_exceptions=None,
suppress_validation_exceptions=None,
components_cache_max_age=None,
**kwargs):

Expand DownExpand Up@@ -126,6 +131,10 @@ def __init__(
'suppress_callback_exceptions',
suppress_callback_exceptions, env_configs, False
),
'suppress_validation_exceptions': _configs.get_config(
Comment thread
rmarren1 marked this conversation as resolved.
'suppress_validation_exceptions',
suppress_validation_exceptions, env_configs, False
),
'routes_pathname_prefix': routes_pathname_prefix,
'requests_pathname_prefix': requests_pathname_prefix,
'include_assets_files': _configs.get_config(
Expand DownExpand Up@@ -168,6 +177,7 @@ def _handle_error(error):
self.assets_ignore = assets_ignore

self.registered_paths = {}
self.namespaces = {}

# urls
self.routes = []
Expand DownExpand Up@@ -256,7 +266,6 @@ def layout(self, value):
'a dash component.')

self._layout = value

layout_value = self._layout_value()
# pylint: disable=protected-access
self.css._update_layout(layout_value)
Expand DownExpand Up@@ -575,7 +584,7 @@ def react(self, *args, **kwargs):
'Use `callback` instead. `callback` has a new syntax too, '
'so make sure to call `help(app.callback)` to learn more.')

def _validate_callback(self, output, inputs, state, events):
def _validate_callback_definition(self, output, inputs, state, events):
# pylint: disable=too-many-branches
layout = self._cached_layout or self._layout_value()

Expand DownExpand Up@@ -713,7 +722,7 @@ def _validate_callback(self, output, inputs, state, events):
output.component_id,
output.component_property).replace(' ', ''))

def _validate_callback_output(self, output_value, output):
def _debug_callback_serialization_error(self, output_value, output):
valid = [str, dict, int, float, type(None), Component]

def _raise_invalid(bad_val, outer_val, bad_type, path, index=None,
Expand DownExpand Up@@ -831,7 +840,7 @@ def _validate_value(val, index=None):
# relationships
# pylint: disable=dangerous-default-value
def callback(self, output, inputs=[], state=[], events=[]):
self._validate_callback(output, inputs, state, events)
self._validate_callback_definition(output, inputs, state, events)

callback_id = '{}.{}'.format(
output.component_id, output.component_property
Expand All@@ -853,13 +862,11 @@ def callback(self, output, inputs=[], state=[], events=[]):

def wrap_func(func):
@wraps(func)
def add_context(*args, **kwargs):

output_value = func(*args, **kwargs)
def add_context(validated_output):
response = {
'response': {
'props': {
output.component_property: output_value
output.component_property: validated_output
}
}
}
Expand All@@ -870,7 +877,10 @@ def add_context(*args, **kwargs):
cls=plotly.utils.PlotlyJSONEncoder
)
except TypeError:
self._validate_callback_output(output_value, output)
self._debug_callback_serialization_error(
validated_output,
output
)
raise exceptions.InvalidCallbackReturnValue('''
The callback for property `{property:s}`
of component `{id:s}` returned a value
Expand All@@ -887,6 +897,7 @@ def add_context(*args, **kwargs):
mimetype='application/json'
)

self.callback_map[callback_id]['func'] = func
self.callback_map[callback_id]['callback'] = add_context

return add_context
Expand DownExpand Up@@ -915,7 +926,88 @@ def dispatch(self):
c['id'] == component_registration['id']
][0])

return self.callback_map[target_id]['callback'](*args)
output_value = self.callback_map[target_id]['func'](*args)

# Only validate if we get required information from renderer
# and validation is not turned off by user
if (
(not self.config.suppress_validation_exceptions) and
Comment thread
rmarren1 marked this conversation as resolved.
'namespace' in output and
'type' in output
):
# Python2.7 might make these keys and values unicode
namespace = str(output['namespace'])
component_type = str(output['type'])
component_id = str(output['id'])
component_property = str(output['property'])
callback_func_name = self.callback_map[target_id]['func'].__name__
self._validate_callback_output(namespace, component_type,
component_id, component_property,
callback_func_name,
args, output_value)

return self.callback_map[target_id]['callback'](output_value)

def _validate_callback_output(self, namespace, component_type,
component_id, component_property,
callback_func_name, args, value):
module = sys.modules[namespace]
Comment thread
rmarren1 marked this conversation as resolved.
component = getattr(module, component_type)
# pylint: disable=protected-access
validator = DashValidator({
component_property: component._schema.get(component_property, {})
})
valid = validator.validate({component_property: value})
if not valid:
error_message = dedent("""\

A Dash Callback produced an invalid value!

Dash tried to update the `{component_property}` prop of the
`{component_name}` with id `{component_id}` by calling the
`{callback_func_name}` function with `{args}` as arguments.

This function call returned `{value}`, which did not pass
validation tests for the `{component_name}` component.

The expected schema for the `{component_property}` prop of the
`{component_name}` component is:

***************************************************************
{component_schema}
***************************************************************

The errors in validation are as follows:

""").format(
component_property=component_property,
component_name=component.__name__,
component_id=component_id,
callback_func_name=callback_func_name,
args='({})'.format(", ".join(map(repr, args))),
value=value,
component_schema=pprint.pformat(
component._schema[component_property]
)
)

error_message = generate_validation_error_message(
validator.errors,
0,
error_message
) + dedent("""
You can turn off these validation exceptions by setting
`app.config.suppress_validation_exceptions=True`
Comment thread
rmarren1 marked this conversation as resolved.
""")

raise exceptions.CallbackOutputValidationError(error_message)
# Must also validate initialization of newly created components
if component_property == 'children':
if isinstance(value, Component):
value.validate()
for component in value.traverse():
if isinstance(component, Component):
component.validate()

def _validate_layout(self):
if self.layout is None:
Expand All@@ -932,6 +1024,11 @@ def _validate_layout(self):

component_ids = {layout_id} if layout_id else set()
for component in to_validate.traverse():
if (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Normally there is no () after if in python.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how else to style since the if statement is > 80 characters. PEP isn't super specific about what to do here: https://www.python.org/dev/peps/pep-0008/#multiline-if-statements.

not self.config.suppress_validation_exceptions and
isinstance(component, Component)
):
component.validate()
component_id = getattr(component, 'id', None)
if component_id and component_id in component_ids:
raise exceptions.DuplicateIdError(
Expand DownExpand Up@@ -1057,5 +1154,9 @@ def run_server(self,
:return:
"""
debug = self.enable_dev_tools(debug, dev_tools_serve_dev_bundles)
if not debug:
# Do not throw debugging exceptions in production.
self.config.suppress_validation_exceptions = True
self.config.suppress_callback_exceptions = True
self.server.run(port=port, debug=debug,
**flask_run_options)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
96 commits
Select commit Hold shift + click to select a range
49d8c21
Update layout on server with each callback, for ids in initial layout.
rmarren1 Aug 15, 2018
12dc611
Update layout for dynamically created elements with ids.
rmarren1 Aug 15, 2018
a0e2f4f
Cerberus validation of initial layout.
rmarren1 Aug 16, 2018
7eb0dbd
Recursive schema generation, schema test case.
rmarren1 Aug 18, 2018
a3ccd76
Custom validation
rmarren1 Aug 23, 2018
377ec7b
Fix validation import
rmarren1 Aug 23, 2018
ce2a255
Merge branch 'master' into validate
rmarren1 Aug 26, 2018
9d0fa01
Make test cases pass
rmarren1 Aug 26, 2018
5665fa4
Fix pylint errors
rmarren1 Aug 26, 2018
f88b068
iteritems -> items for python3 compatibility.
rmarren1 Aug 26, 2018
6205742
Fix unicode and ordering issues with oyaml.
rmarren1 Aug 27, 2018
6b65a67
use dash-renderer version with namespace and type
rmarren1 Aug 27, 2018
4df2bb8
Only validate if 'namespace' and 'type' in json body.
rmarren1 Aug 27, 2018
9e5aa93
Change loader back to json, add hook to transform unicode to string.
rmarren1 Aug 28, 2018
b045753
Do not try to match schema string exactly.
rmarren1 Aug 28, 2018
89d7137
Component validation test cases
rmarren1 Aug 29, 2018
ffd63ba
Required prop type test case
rmarren1 Aug 29, 2018
954aae3
Pylint fixes
rmarren1 Aug 29, 2018
93d4bf6
Fix dict
rmarren1 Aug 29, 2018
a934c26
Improve error message, custom exceptions.
rmarren1 Aug 29, 2018
4bb97ef
Figure validation
rmarren1 Aug 30, 2018
4cb76fe
Fix import order for Pylint.
rmarren1 Aug 30, 2018
233c145
Extra newlines in exceptions for Pylint.
rmarren1 Aug 30, 2018
cf47627
Rename exceptions import for Pylint.
rmarren1 Aug 30, 2018
2817398
Only validate against callback property.
rmarren1 Aug 30, 2018
ee3d1ab
Allow 'None' in children lists.
rmarren1 Aug 30, 2018
9240436
If prop doesn't exist in schema, don't validate callback (for wildcards)
rmarren1 Aug 30, 2018
1373fc2
Fix tests.
rmarren1 Aug 30, 2018
7e804d0
Fix Pylint.
rmarren1 Aug 30, 2018
bc947e6
Add Plotly Figure validation correctly, print error from Plotly.py
rmarren1 Aug 30, 2018
c9b693b
Update renderer requirement
rmarren1 Aug 30, 2018
6c37980
Workaround for PropTypes.null
rmarren1 Sep 2, 2018
fa74afd
Allow 'None' in children arrays.
rmarren1 Sep 3, 2018
5bcec21
Merge branch 'master' into validate
rmarren1 Sep 3, 2018
dd13a80
Fix test cases
rmarren1 Sep 3, 2018
0a33769
Bump dash-html-components version to version published from 3.7.
rmarren1 Sep 5, 2018
c42c3d5
Update integration tests.
rmarren1 Sep 5, 2018
19910ad
Try not installing virtualenv
rmarren1 Sep 6, 2018
4b02ddb
Try venv in home directory
rmarren1 Sep 6, 2018
fcbebd9
Update plotly figure validator.
rmarren1 Sep 7, 2018
54558fe
Bump version and fix pylint
rmarren1 Sep 7, 2018
603aac2
Bump core component versions.
rmarren1 Sep 7, 2018
f6ecaa7
'{}' is not a valid figure.
rmarren1 Sep 7, 2018
5d7625a
Fix figure validator and bump dash-core-components version.
rmarren1 Sep 7, 2018
357ee94
Update wildcard callback test.
rmarren1 Sep 7, 2018
f067f91
Merge branch 'master' into validate
rmarren1 Sep 7, 2018
9b5b9f2
Add Cerberus to dev requirements files
rmarren1 Sep 7, 2018
f6c15da
Allow for required `children`.
rmarren1 Sep 20, 2018
f99490f
Pylint fixes
rmarren1 Sep 21, 2018
886c83a
Merge branch 'master' into validate
rmarren1 Sep 21, 2018
e75d6f1
Fix circle
rmarren1 Sep 21, 2018
8d1727e
Ignore too-many-lines
rmarren1 Sep 21, 2018
87db60a
disable too many lines in .pylintrc
rmarren1 Sep 21, 2018
6967dad
too many lines in .pylint37 too
rmarren1 Sep 21, 2018
42fab98
Add tests for numpy ndarray / pandas series as list.
rmarren1 Sep 28, 2018
06682d2
Update list validator to work for pd.Series, np.ndarray
rmarren1 Sep 28, 2018
906e7c9
Add tests for int / float in enum.
rmarren1 Sep 28, 2018
03a7c08
Update enum to work with int / float
rmarren1 Sep 28, 2018
b1d1337
Add tests for numpy int / float
rmarren1 Sep 28, 2018
426e4f3
Update number validation to support numpy int / float
rmarren1 Sep 28, 2018
b0b5385
Change name `_validate_callback` -> `_validate_callback_definition`
rmarren1 Oct 1, 2018
d98a1a7
`_validate_callback_output` -> `_validate_callback_serialization_error`
rmarren1 Oct 1, 2018
0523beb
Add initial layout validation test.
rmarren1 Oct 1, 2018
b5b7935
Move validation to method in base component.
rmarren1 Oct 1, 2018
d8eb35f
Add disable_component_validation config option.
rmarren1 Oct 1, 2018
b8e2c67
Run component validation on initial layout.
rmarren1 Oct 1, 2018
0fd11b7
Update initial layout validation test.
rmarren1 Oct 1, 2018
2049dfb
Add callback output validation test.
rmarren1 Oct 2, 2018
a3d1402
Bump dash-html-component version in dev.
rmarren1 Oct 2, 2018
015674e
Move component validation to its own method.
rmarren1 Oct 2, 2018
8c2d97f
Move initial layout test, add initialization in callback test
rmarren1 Oct 2, 2018
9fcfa96
Change name of initialization validation error
rmarren1 Oct 2, 2018
95f20cd
Add callback component initialization validation
rmarren1 Oct 2, 2018
f92812b
Make sure children is component before validation.
rmarren1 Oct 2, 2018
0a57cc5
Add Cerberus to setup.py install_requires.
rmarren1 Oct 5, 2018
64b4f5c
Give more information in validation error messages.
rmarren1 Oct 5, 2018
0a515d2
` -> * for error message blocks, so you can copy paste to github.
rmarren1 Oct 5, 2018
dce6a06
Rebase
rmarren1 Oct 18, 2018
708c2f7
Un-comment broken test.
rmarren1 Oct 18, 2018
c8f2953
Add test for using boolean in enum
rmarren1 Oct 18, 2018
c64bc6d
Update Table test component for boolean enum values
rmarren1 Oct 18, 2018
8202256
Forgot to add changed metadata_test.py file (Table component)
rmarren1 Oct 18, 2018
e3aa8d9
Add support for boolean in enum to schema generation.
rmarren1 Oct 18, 2018
f9db291
Add a test for 'options_with_unique_values' validator.
rmarren1 Oct 19, 2018
41d0e81
Add 'options_with_unique_values' validator.
rmarren1 Oct 19, 2018
616583a
lines too long fixes.
rmarren1 Oct 19, 2018
588ce3d
pylint fixes
rmarren1 Oct 19, 2018
cead8e7
Rebase
rmarren1 Nov 2, 2018
9962b2a
Change `disable_component_validation` to `suppress_validation_callbacks`
rmarren1 Nov 2, 2018
3bcfefb
Small typo in test react component
rmarren1 Nov 2, 2018
a5093a0
Monkey patch schemas onto dash_html_components for test
rmarren1 Nov 2, 2018
4af81bf
Use sys.modules rather than dynamic import.
rmarren1 Nov 2, 2018
d81fadb
Disable validation exceptions when in production.
rmarren1 Nov 2, 2018
944bcc3
Tell user how to turn off validation exceptions in the message.
rmarren1 Nov 2, 2018
b785e1b
Pylint fixes
rmarren1 Nov 2, 2018
ea5cf00
Fix line too long
rmarren1 Nov 2, 2018
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .circleci/config.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -49,6 +49,7 @@ jobs:
python --version
python -m unittest tests.development.test_base_component
python -m unittest tests.development.test_component_loader
python -m unittest tests.development.test_component_validation
python -m unittest tests.test_integration
python -m unittest tests.test_resources
python -m unittest tests.test_configs
Expand Down
3 changes: 3 additions & 0 deletions .circleci/requirements/dev-requirements-py37.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,8 +9,11 @@ mock
tox
tox-pyenv
six
numpy
pandas
plotly>=2.0.8
requests[security]
flake8
pylint==2.1.1
astroid==2.0.4
Cerberus==1.2
3 changes: 3 additions & 0 deletions .circleci/requirements/dev-requirements.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,7 +10,10 @@ tox
tox-pyenv
mock
six
numpy
pandas
plotly>=2.0.8
requests[security]
flake8
pylint==1.9.2
Cerberus==1.2
1 change: 1 addition & 0 deletions .pylintrc37
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,6 +63,7 @@ confidence=
disable=invalid-name,
missing-docstring,
print-statement,
too-many-lines,
parameter-unpacking,
unpacking-in-except,
old-raise-syntax,
Expand Down
121 changes: 111 additions & 10 deletions dash/dash.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,11 +5,13 @@
import collections
import importlib
import json
import pprint
import pkgutil
import warnings
import re

from functools import wraps
from textwrap import dedent

import plotly
import dash_renderer
Expand All@@ -20,6 +22,8 @@
from .dependencies import Event, Input, Output, State
from .resources import Scripts, Css
from .development.base_component import Component
from .development.validator import (DashValidator,
generate_validation_error_message)
from . import exceptions
from ._utils import AttributeDict as _AttributeDict
from ._utils import interpolate_str as _interpolate
Expand DownExpand Up@@ -84,6 +88,7 @@ def __init__(
external_scripts=None,
external_stylesheets=None,
suppress_callback_exceptions=None,
suppress_validation_exceptions=None,
components_cache_max_age=None,
**kwargs):

Expand DownExpand Up@@ -126,6 +131,10 @@ def __init__(
'suppress_callback_exceptions',
suppress_callback_exceptions, env_configs, False
),
'suppress_validation_exceptions': _configs.get_config(
Comment thread
rmarren1 marked this conversation as resolved.
'suppress_validation_exceptions',
suppress_validation_exceptions, env_configs, False
),
'routes_pathname_prefix': routes_pathname_prefix,
'requests_pathname_prefix': requests_pathname_prefix,
'include_assets_files': _configs.get_config(
Expand DownExpand Up@@ -168,6 +177,7 @@ def _handle_error(error):
self.assets_ignore = assets_ignore

self.registered_paths = {}
self.namespaces = {}

# urls
self.routes = []
Expand DownExpand Up@@ -256,7 +266,6 @@ def layout(self, value):
'a dash component.')

self._layout = value

layout_value = self._layout_value()
# pylint: disable=protected-access
self.css._update_layout(layout_value)
Expand DownExpand Up@@ -575,7 +584,7 @@ def react(self, *args, **kwargs):
'Use `callback` instead. `callback` has a new syntax too, '
'so make sure to call `help(app.callback)` to learn more.')

def _validate_callback(self, output, inputs, state, events):
def _validate_callback_definition(self, output, inputs, state, events):
# pylint: disable=too-many-branches
layout = self._cached_layout or self._layout_value()

Expand DownExpand Up@@ -713,7 +722,7 @@ def _validate_callback(self, output, inputs, state, events):
output.component_id,
output.component_property).replace(' ', ''))

def _validate_callback_output(self, output_value, output):
def _debug_callback_serialization_error(self, output_value, output):
valid = [str, dict, int, float, type(None), Component]

def _raise_invalid(bad_val, outer_val, bad_type, path, index=None,
Expand DownExpand Up@@ -831,7 +840,7 @@ def _validate_value(val, index=None):
# relationships
# pylint: disable=dangerous-default-value
def callback(self, output, inputs=[], state=[], events=[]):
self._validate_callback(output, inputs, state, events)
self._validate_callback_definition(output, inputs, state, events)

callback_id = '{}.{}'.format(
output.component_id, output.component_property
Expand All@@ -853,13 +862,11 @@ def callback(self, output, inputs=[], state=[], events=[]):

def wrap_func(func):
@wraps(func)
def add_context(*args, **kwargs):

output_value = func(*args, **kwargs)
def add_context(validated_output):
response = {
'response': {
'props': {
output.component_property: output_value
output.component_property: validated_output
}
}
}
Expand All@@ -870,7 +877,10 @@ def add_context(*args, **kwargs):
cls=plotly.utils.PlotlyJSONEncoder
)
except TypeError:
self._validate_callback_output(output_value, output)
self._debug_callback_serialization_error(
validated_output,
output
)
raise exceptions.InvalidCallbackReturnValue('''
The callback for property `{property:s}`
of component `{id:s}` returned a value
Expand All@@ -887,6 +897,7 @@ def add_context(*args, **kwargs):
mimetype='application/json'
)

self.callback_map[callback_id]['func'] = func
self.callback_map[callback_id]['callback'] = add_context

return add_context
Expand DownExpand Up@@ -915,7 +926,88 @@ def dispatch(self):
c['id'] == component_registration['id']
][0])

return self.callback_map[target_id]['callback'](*args)
output_value = self.callback_map[target_id]['func'](*args)

# Only validate if we get required information from renderer
# and validation is not turned off by user
if (
(not self.config.suppress_validation_exceptions) and
Comment thread
rmarren1 marked this conversation as resolved.
'namespace' in output and
'type' in output
):
# Python2.7 might make these keys and values unicode
namespace = str(output['namespace'])
component_type = str(output['type'])
component_id = str(output['id'])
component_property = str(output['property'])
callback_func_name = self.callback_map[target_id]['func'].__name__
self._validate_callback_output(namespace, component_type,
component_id, component_property,
callback_func_name,
args, output_value)

return self.callback_map[target_id]['callback'](output_value)

def _validate_callback_output(self, namespace, component_type,
component_id, component_property,
callback_func_name, args, value):
module = sys.modules[namespace]
Comment thread
rmarren1 marked this conversation as resolved.
component = getattr(module, component_type)
# pylint: disable=protected-access
validator = DashValidator({
component_property: component._schema.get(component_property, {})
})
valid = validator.validate({component_property: value})
if not valid:
error_message = dedent("""\

A Dash Callback produced an invalid value!

Dash tried to update the `{component_property}` prop of the
`{component_name}` with id `{component_id}` by calling the
`{callback_func_name}` function with `{args}` as arguments.

This function call returned `{value}`, which did not pass
validation tests for the `{component_name}` component.

The expected schema for the `{component_property}` prop of the
`{component_name}` component is:

***************************************************************
{component_schema}
***************************************************************

The errors in validation are as follows:

""").format(
component_property=component_property,
component_name=component.__name__,
component_id=component_id,
callback_func_name=callback_func_name,
args='({})'.format(", ".join(map(repr, args))),
value=value,
component_schema=pprint.pformat(
component._schema[component_property]
)
)

error_message = generate_validation_error_message(
validator.errors,
0,
error_message
) + dedent("""
You can turn off these validation exceptions by setting
`app.config.suppress_validation_exceptions=True`
Comment thread
rmarren1 marked this conversation as resolved.
""")

raise exceptions.CallbackOutputValidationError(error_message)
# Must also validate initialization of newly created components
if component_property == 'children':
if isinstance(value, Component):
value.validate()
for component in value.traverse():
if isinstance(component, Component):
component.validate()

def _validate_layout(self):
if self.layout is None:
Expand All@@ -932,6 +1024,11 @@ def _validate_layout(self):

component_ids = {layout_id} if layout_id else set()
for component in to_validate.traverse():
if (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Normally there is no () after if in python.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how else to style since the if statement is > 80 characters. PEP isn't super specific about what to do here: https://www.python.org/dev/peps/pep-0008/#multiline-if-statements.

not self.config.suppress_validation_exceptions and
isinstance(component, Component)
):
component.validate()
component_id = getattr(component, 'id', None)
if component_id and component_id in component_ids:
raise exceptions.DuplicateIdError(
Expand DownExpand Up@@ -1057,5 +1154,9 @@ def run_server(self,
:return:
"""
debug = self.enable_dev_tools(debug, dev_tools_serve_dev_bundles)
if not debug:
# Do not throw debugging exceptions in production.
self.config.suppress_validation_exceptions = True
self.config.suppress_callback_exceptions = True
self.server.run(port=port, debug=debug,
**flask_run_options)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
96 commits
Select commit Hold shift + click to select a range
49d8c21
Update layout on server with each callback, for ids in initial layout.
rmarren1 Aug 15, 2018
12dc611
Update layout for dynamically created elements with ids.
rmarren1 Aug 15, 2018
a0e2f4f
Cerberus validation of initial layout.
rmarren1 Aug 16, 2018
7eb0dbd
Recursive schema generation, schema test case.
rmarren1 Aug 18, 2018
a3ccd76
Custom validation
rmarren1 Aug 23, 2018
377ec7b
Fix validation import
rmarren1 Aug 23, 2018
ce2a255
Merge branch 'master' into validate
rmarren1 Aug 26, 2018
9d0fa01
Make test cases pass
rmarren1 Aug 26, 2018
5665fa4
Fix pylint errors
rmarren1 Aug 26, 2018
f88b068
iteritems -> items for python3 compatibility.
rmarren1 Aug 26, 2018
6205742
Fix unicode and ordering issues with oyaml.
rmarren1 Aug 27, 2018
6b65a67
use dash-renderer version with namespace and type
rmarren1 Aug 27, 2018
4df2bb8
Only validate if 'namespace' and 'type' in json body.
rmarren1 Aug 27, 2018
9e5aa93
Change loader back to json, add hook to transform unicode to string.
rmarren1 Aug 28, 2018
b045753
Do not try to match schema string exactly.
rmarren1 Aug 28, 2018
89d7137
Component validation test cases
rmarren1 Aug 29, 2018
ffd63ba
Required prop type test case
rmarren1 Aug 29, 2018
954aae3
Pylint fixes
rmarren1 Aug 29, 2018
93d4bf6
Fix dict
rmarren1 Aug 29, 2018
a934c26
Improve error message, custom exceptions.
rmarren1 Aug 29, 2018
4bb97ef
Figure validation
rmarren1 Aug 30, 2018
4cb76fe
Fix import order for Pylint.
rmarren1 Aug 30, 2018
233c145
Extra newlines in exceptions for Pylint.
rmarren1 Aug 30, 2018
cf47627
Rename exceptions import for Pylint.
rmarren1 Aug 30, 2018
2817398
Only validate against callback property.
rmarren1 Aug 30, 2018
ee3d1ab
Allow 'None' in children lists.
rmarren1 Aug 30, 2018
9240436
If prop doesn't exist in schema, don't validate callback (for wildcards)
rmarren1 Aug 30, 2018
1373fc2
Fix tests.
rmarren1 Aug 30, 2018
7e804d0
Fix Pylint.
rmarren1 Aug 30, 2018
bc947e6
Add Plotly Figure validation correctly, print error from Plotly.py
rmarren1 Aug 30, 2018
c9b693b
Update renderer requirement
rmarren1 Aug 30, 2018
6c37980
Workaround for PropTypes.null
rmarren1 Sep 2, 2018
fa74afd
Allow 'None' in children arrays.
rmarren1 Sep 3, 2018
5bcec21
Merge branch 'master' into validate
rmarren1 Sep 3, 2018
dd13a80
Fix test cases
rmarren1 Sep 3, 2018
0a33769
Bump dash-html-components version to version published from 3.7.
rmarren1 Sep 5, 2018
c42c3d5
Update integration tests.
rmarren1 Sep 5, 2018
19910ad
Try not installing virtualenv
rmarren1 Sep 6, 2018
4b02ddb
Try venv in home directory
rmarren1 Sep 6, 2018
fcbebd9
Update plotly figure validator.
rmarren1 Sep 7, 2018
54558fe
Bump version and fix pylint
rmarren1 Sep 7, 2018
603aac2
Bump core component versions.
rmarren1 Sep 7, 2018
f6ecaa7
'{}' is not a valid figure.
rmarren1 Sep 7, 2018
5d7625a
Fix figure validator and bump dash-core-components version.
rmarren1 Sep 7, 2018
357ee94
Update wildcard callback test.
rmarren1 Sep 7, 2018
f067f91
Merge branch 'master' into validate
rmarren1 Sep 7, 2018
9b5b9f2
Add Cerberus to dev requirements files
rmarren1 Sep 7, 2018
f6c15da
Allow for required `children`.
rmarren1 Sep 20, 2018
f99490f
Pylint fixes
rmarren1 Sep 21, 2018
886c83a
Merge branch 'master' into validate
rmarren1 Sep 21, 2018
e75d6f1
Fix circle
rmarren1 Sep 21, 2018
8d1727e
Ignore too-many-lines
rmarren1 Sep 21, 2018
87db60a
disable too many lines in .pylintrc
rmarren1 Sep 21, 2018
6967dad
too many lines in .pylint37 too
rmarren1 Sep 21, 2018
42fab98
Add tests for numpy ndarray / pandas series as list.
rmarren1 Sep 28, 2018
06682d2
Update list validator to work for pd.Series, np.ndarray
rmarren1 Sep 28, 2018
906e7c9
Add tests for int / float in enum.
rmarren1 Sep 28, 2018
03a7c08
Update enum to work with int / float
rmarren1 Sep 28, 2018
b1d1337
Add tests for numpy int / float
rmarren1 Sep 28, 2018
426e4f3
Update number validation to support numpy int / float
rmarren1 Sep 28, 2018
b0b5385
Change name `_validate_callback` -> `_validate_callback_definition`
rmarren1 Oct 1, 2018
d98a1a7
`_validate_callback_output` -> `_validate_callback_serialization_error`
rmarren1 Oct 1, 2018
0523beb
Add initial layout validation test.
rmarren1 Oct 1, 2018
b5b7935
Move validation to method in base component.
rmarren1 Oct 1, 2018
d8eb35f
Add disable_component_validation config option.
rmarren1 Oct 1, 2018
b8e2c67
Run component validation on initial layout.
rmarren1 Oct 1, 2018
0fd11b7
Update initial layout validation test.
rmarren1 Oct 1, 2018
2049dfb
Add callback output validation test.
rmarren1 Oct 2, 2018
a3d1402
Bump dash-html-component version in dev.
rmarren1 Oct 2, 2018
015674e
Move component validation to its own method.
rmarren1 Oct 2, 2018
8c2d97f
Move initial layout test, add initialization in callback test
rmarren1 Oct 2, 2018
9fcfa96
Change name of initialization validation error
rmarren1 Oct 2, 2018
95f20cd
Add callback component initialization validation
rmarren1 Oct 2, 2018
f92812b
Make sure children is component before validation.
rmarren1 Oct 2, 2018
0a57cc5
Add Cerberus to setup.py install_requires.
rmarren1 Oct 5, 2018
64b4f5c
Give more information in validation error messages.
rmarren1 Oct 5, 2018
0a515d2
` -> * for error message blocks, so you can copy paste to github.
rmarren1 Oct 5, 2018
dce6a06
Rebase
rmarren1 Oct 18, 2018
708c2f7
Un-comment broken test.
rmarren1 Oct 18, 2018
c8f2953
Add test for using boolean in enum
rmarren1 Oct 18, 2018
c64bc6d
Update Table test component for boolean enum values
rmarren1 Oct 18, 2018
8202256
Forgot to add changed metadata_test.py file (Table component)
rmarren1 Oct 18, 2018
e3aa8d9
Add support for boolean in enum to schema generation.
rmarren1 Oct 18, 2018
f9db291
Add a test for 'options_with_unique_values' validator.
rmarren1 Oct 19, 2018
41d0e81
Add 'options_with_unique_values' validator.
rmarren1 Oct 19, 2018
616583a
lines too long fixes.
rmarren1 Oct 19, 2018
588ce3d
pylint fixes
rmarren1 Oct 19, 2018
cead8e7
Rebase
rmarren1 Nov 2, 2018
9962b2a
Change `disable_component_validation` to `suppress_validation_callbacks`
rmarren1 Nov 2, 2018
3bcfefb
Small typo in test react component
rmarren1 Nov 2, 2018
a5093a0
Monkey patch schemas onto dash_html_components for test
rmarren1 Nov 2, 2018
4af81bf
Use sys.modules rather than dynamic import.
rmarren1 Nov 2, 2018
d81fadb
Disable validation exceptions when in production.
rmarren1 Nov 2, 2018
944bcc3
Tell user how to turn off validation exceptions in the message.
rmarren1 Nov 2, 2018
b785e1b
Pylint fixes
rmarren1 Nov 2, 2018
ea5cf00
Fix line too long
rmarren1 Nov 2, 2018
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .circleci/config.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -49,6 +49,7 @@ jobs:
python --version
python -m unittest tests.development.test_base_component
python -m unittest tests.development.test_component_loader
python -m unittest tests.development.test_component_validation
python -m unittest tests.test_integration
python -m unittest tests.test_resources
python -m unittest tests.test_configs
Expand Down
3 changes: 3 additions & 0 deletions .circleci/requirements/dev-requirements-py37.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,8 +9,11 @@ mock
tox
tox-pyenv
six
numpy
pandas
plotly>=2.0.8
requests[security]
flake8
pylint==2.1.1
astroid==2.0.4
Cerberus==1.2
3 changes: 3 additions & 0 deletions .circleci/requirements/dev-requirements.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,7 +10,10 @@ tox
tox-pyenv
mock
six
numpy
pandas
plotly>=2.0.8
requests[security]
flake8
pylint==1.9.2
Cerberus==1.2
1 change: 1 addition & 0 deletions .pylintrc37
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,6 +63,7 @@ confidence=
disable=invalid-name,
missing-docstring,
print-statement,
too-many-lines,
parameter-unpacking,
unpacking-in-except,
old-raise-syntax,
Expand Down
121 changes: 111 additions & 10 deletions dash/dash.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,11 +5,13 @@
import collections
import importlib
import json
import pprint
import pkgutil
import warnings
import re

from functools import wraps
from textwrap import dedent

import plotly
import dash_renderer
Expand All@@ -20,6 +22,8 @@
from .dependencies import Event, Input, Output, State
from .resources import Scripts, Css
from .development.base_component import Component
from .development.validator import (DashValidator,
generate_validation_error_message)
from . import exceptions
from ._utils import AttributeDict as _AttributeDict
from ._utils import interpolate_str as _interpolate
Expand DownExpand Up@@ -84,6 +88,7 @@ def __init__(
external_scripts=None,
external_stylesheets=None,
suppress_callback_exceptions=None,
suppress_validation_exceptions=None,
components_cache_max_age=None,
**kwargs):

Expand DownExpand Up@@ -126,6 +131,10 @@ def __init__(
'suppress_callback_exceptions',
suppress_callback_exceptions, env_configs, False
),
'suppress_validation_exceptions': _configs.get_config(
Comment thread
rmarren1 marked this conversation as resolved.
'suppress_validation_exceptions',
suppress_validation_exceptions, env_configs, False
),
'routes_pathname_prefix': routes_pathname_prefix,
'requests_pathname_prefix': requests_pathname_prefix,
'include_assets_files': _configs.get_config(
Expand DownExpand Up@@ -168,6 +177,7 @@ def _handle_error(error):
self.assets_ignore = assets_ignore

self.registered_paths = {}
self.namespaces = {}

# urls
self.routes = []
Expand DownExpand Up@@ -256,7 +266,6 @@ def layout(self, value):
'a dash component.')

self._layout = value

layout_value = self._layout_value()
# pylint: disable=protected-access
self.css._update_layout(layout_value)
Expand DownExpand Up@@ -575,7 +584,7 @@ def react(self, *args, **kwargs):
'Use `callback` instead. `callback` has a new syntax too, '
'so make sure to call `help(app.callback)` to learn more.')

def _validate_callback(self, output, inputs, state, events):
def _validate_callback_definition(self, output, inputs, state, events):
# pylint: disable=too-many-branches
layout = self._cached_layout or self._layout_value()

Expand DownExpand Up@@ -713,7 +722,7 @@ def _validate_callback(self, output, inputs, state, events):
output.component_id,
output.component_property).replace(' ', ''))

def _validate_callback_output(self, output_value, output):
def _debug_callback_serialization_error(self, output_value, output):
valid = [str, dict, int, float, type(None), Component]

def _raise_invalid(bad_val, outer_val, bad_type, path, index=None,
Expand DownExpand Up@@ -831,7 +840,7 @@ def _validate_value(val, index=None):
# relationships
# pylint: disable=dangerous-default-value
def callback(self, output, inputs=[], state=[], events=[]):
self._validate_callback(output, inputs, state, events)
self._validate_callback_definition(output, inputs, state, events)

callback_id = '{}.{}'.format(
output.component_id, output.component_property
Expand All@@ -853,13 +862,11 @@ def callback(self, output, inputs=[], state=[], events=[]):

def wrap_func(func):
@wraps(func)
def add_context(*args, **kwargs):

output_value = func(*args, **kwargs)
def add_context(validated_output):
response = {
'response': {
'props': {
output.component_property: output_value
output.component_property: validated_output
}
}
}
Expand All@@ -870,7 +877,10 @@ def add_context(*args, **kwargs):
cls=plotly.utils.PlotlyJSONEncoder
)
except TypeError:
self._validate_callback_output(output_value, output)
self._debug_callback_serialization_error(
validated_output,
output
)
raise exceptions.InvalidCallbackReturnValue('''
The callback for property `{property:s}`
of component `{id:s}` returned a value
Expand All@@ -887,6 +897,7 @@ def add_context(*args, **kwargs):
mimetype='application/json'
)

self.callback_map[callback_id]['func'] = func
self.callback_map[callback_id]['callback'] = add_context

return add_context
Expand DownExpand Up@@ -915,7 +926,88 @@ def dispatch(self):
c['id'] == component_registration['id']
][0])

return self.callback_map[target_id]['callback'](*args)
output_value = self.callback_map[target_id]['func'](*args)

# Only validate if we get required information from renderer
# and validation is not turned off by user
if (
(not self.config.suppress_validation_exceptions) and
Comment thread
rmarren1 marked this conversation as resolved.
'namespace' in output and
'type' in output
):
# Python2.7 might make these keys and values unicode
namespace = str(output['namespace'])
component_type = str(output['type'])
component_id = str(output['id'])
component_property = str(output['property'])
callback_func_name = self.callback_map[target_id]['func'].__name__
self._validate_callback_output(namespace, component_type,
component_id, component_property,
callback_func_name,
args, output_value)

return self.callback_map[target_id]['callback'](output_value)

def _validate_callback_output(self, namespace, component_type,
component_id, component_property,
callback_func_name, args, value):
module = sys.modules[namespace]
Comment thread
rmarren1 marked this conversation as resolved.
component = getattr(module, component_type)
# pylint: disable=protected-access
validator = DashValidator({
component_property: component._schema.get(component_property, {})
})
valid = validator.validate({component_property: value})
if not valid:
error_message = dedent("""\

A Dash Callback produced an invalid value!

Dash tried to update the `{component_property}` prop of the
`{component_name}` with id `{component_id}` by calling the
`{callback_func_name}` function with `{args}` as arguments.

This function call returned `{value}`, which did not pass
validation tests for the `{component_name}` component.

The expected schema for the `{component_property}` prop of the
`{component_name}` component is:

***************************************************************
{component_schema}
***************************************************************

The errors in validation are as follows:

""").format(
component_property=component_property,
component_name=component.__name__,
component_id=component_id,
callback_func_name=callback_func_name,
args='({})'.format(", ".join(map(repr, args))),
value=value,
component_schema=pprint.pformat(
component._schema[component_property]
)
)

error_message = generate_validation_error_message(
validator.errors,
0,
error_message
) + dedent("""
You can turn off these validation exceptions by setting
`app.config.suppress_validation_exceptions=True`
Comment thread
rmarren1 marked this conversation as resolved.
""")

raise exceptions.CallbackOutputValidationError(error_message)
# Must also validate initialization of newly created components
if component_property == 'children':
if isinstance(value, Component):
value.validate()
for component in value.traverse():
if isinstance(component, Component):
component.validate()

def _validate_layout(self):
if self.layout is None:
Expand All@@ -932,6 +1024,11 @@ def _validate_layout(self):

component_ids = {layout_id} if layout_id else set()
for component in to_validate.traverse():
if (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Normally there is no () after if in python.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how else to style since the if statement is > 80 characters. PEP isn't super specific about what to do here: https://www.python.org/dev/peps/pep-0008/#multiline-if-statements.

not self.config.suppress_validation_exceptions and
isinstance(component, Component)
):
component.validate()
component_id = getattr(component, 'id', None)
if component_id and component_id in component_ids:
raise exceptions.DuplicateIdError(
Expand DownExpand Up@@ -1057,5 +1154,9 @@ def run_server(self,
:return:
"""
debug = self.enable_dev_tools(debug, dev_tools_serve_dev_bundles)
if not debug:
# Do not throw debugging exceptions in production.
self.config.suppress_validation_exceptions = True
self.config.suppress_callback_exceptions = True
self.server.run(port=port, debug=debug,
**flask_run_options)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
96 commits
Select commit Hold shift + click to select a range
49d8c21
Update layout on server with each callback, for ids in initial layout.
rmarren1 Aug 15, 2018
12dc611
Update layout for dynamically created elements with ids.
rmarren1 Aug 15, 2018
a0e2f4f
Cerberus validation of initial layout.
rmarren1 Aug 16, 2018
7eb0dbd
Recursive schema generation, schema test case.
rmarren1 Aug 18, 2018
a3ccd76
Custom validation
rmarren1 Aug 23, 2018
377ec7b
Fix validation import
rmarren1 Aug 23, 2018
ce2a255
Merge branch 'master' into validate
rmarren1 Aug 26, 2018
9d0fa01
Make test cases pass
rmarren1 Aug 26, 2018
5665fa4
Fix pylint errors
rmarren1 Aug 26, 2018
f88b068
iteritems -> items for python3 compatibility.
rmarren1 Aug 26, 2018
6205742
Fix unicode and ordering issues with oyaml.
rmarren1 Aug 27, 2018
6b65a67
use dash-renderer version with namespace and type
rmarren1 Aug 27, 2018
4df2bb8
Only validate if 'namespace' and 'type' in json body.
rmarren1 Aug 27, 2018
9e5aa93
Change loader back to json, add hook to transform unicode to string.
rmarren1 Aug 28, 2018
b045753
Do not try to match schema string exactly.
rmarren1 Aug 28, 2018
89d7137
Component validation test cases
rmarren1 Aug 29, 2018
ffd63ba
Required prop type test case
rmarren1 Aug 29, 2018
954aae3
Pylint fixes
rmarren1 Aug 29, 2018
93d4bf6
Fix dict
rmarren1 Aug 29, 2018
a934c26
Improve error message, custom exceptions.
rmarren1 Aug 29, 2018
4bb97ef
Figure validation
rmarren1 Aug 30, 2018
4cb76fe
Fix import order for Pylint.
rmarren1 Aug 30, 2018
233c145
Extra newlines in exceptions for Pylint.
rmarren1 Aug 30, 2018
cf47627
Rename exceptions import for Pylint.
rmarren1 Aug 30, 2018
2817398
Only validate against callback property.
rmarren1 Aug 30, 2018
ee3d1ab
Allow 'None' in children lists.
rmarren1 Aug 30, 2018
9240436
If prop doesn't exist in schema, don't validate callback (for wildcards)
rmarren1 Aug 30, 2018
1373fc2
Fix tests.
rmarren1 Aug 30, 2018
7e804d0
Fix Pylint.
rmarren1 Aug 30, 2018
bc947e6
Add Plotly Figure validation correctly, print error from Plotly.py
rmarren1 Aug 30, 2018
c9b693b
Update renderer requirement
rmarren1 Aug 30, 2018
6c37980
Workaround for PropTypes.null
rmarren1 Sep 2, 2018
fa74afd
Allow 'None' in children arrays.
rmarren1 Sep 3, 2018
5bcec21
Merge branch 'master' into validate
rmarren1 Sep 3, 2018
dd13a80
Fix test cases
rmarren1 Sep 3, 2018
0a33769
Bump dash-html-components version to version published from 3.7.
rmarren1 Sep 5, 2018
c42c3d5
Update integration tests.
rmarren1 Sep 5, 2018
19910ad
Try not installing virtualenv
rmarren1 Sep 6, 2018
4b02ddb
Try venv in home directory
rmarren1 Sep 6, 2018
fcbebd9
Update plotly figure validator.
rmarren1 Sep 7, 2018
54558fe
Bump version and fix pylint
rmarren1 Sep 7, 2018
603aac2
Bump core component versions.
rmarren1 Sep 7, 2018
f6ecaa7
'{}' is not a valid figure.
rmarren1 Sep 7, 2018
5d7625a
Fix figure validator and bump dash-core-components version.
rmarren1 Sep 7, 2018
357ee94
Update wildcard callback test.
rmarren1 Sep 7, 2018
f067f91
Merge branch 'master' into validate
rmarren1 Sep 7, 2018
9b5b9f2
Add Cerberus to dev requirements files
rmarren1 Sep 7, 2018
f6c15da
Allow for required `children`.
rmarren1 Sep 20, 2018
f99490f
Pylint fixes
rmarren1 Sep 21, 2018
886c83a
Merge branch 'master' into validate
rmarren1 Sep 21, 2018
e75d6f1
Fix circle
rmarren1 Sep 21, 2018
8d1727e
Ignore too-many-lines
rmarren1 Sep 21, 2018
87db60a
disable too many lines in .pylintrc
rmarren1 Sep 21, 2018
6967dad
too many lines in .pylint37 too
rmarren1 Sep 21, 2018
42fab98
Add tests for numpy ndarray / pandas series as list.
rmarren1 Sep 28, 2018
06682d2
Update list validator to work for pd.Series, np.ndarray
rmarren1 Sep 28, 2018
906e7c9
Add tests for int / float in enum.
rmarren1 Sep 28, 2018
03a7c08
Update enum to work with int / float
rmarren1 Sep 28, 2018
b1d1337
Add tests for numpy int / float
rmarren1 Sep 28, 2018
426e4f3
Update number validation to support numpy int / float
rmarren1 Sep 28, 2018
b0b5385
Change name `_validate_callback` -> `_validate_callback_definition`
rmarren1 Oct 1, 2018
d98a1a7
`_validate_callback_output` -> `_validate_callback_serialization_error`
rmarren1 Oct 1, 2018
0523beb
Add initial layout validation test.
rmarren1 Oct 1, 2018
b5b7935
Move validation to method in base component.
rmarren1 Oct 1, 2018
d8eb35f
Add disable_component_validation config option.
rmarren1 Oct 1, 2018
b8e2c67
Run component validation on initial layout.
rmarren1 Oct 1, 2018
0fd11b7
Update initial layout validation test.
rmarren1 Oct 1, 2018
2049dfb
Add callback output validation test.
rmarren1 Oct 2, 2018
a3d1402
Bump dash-html-component version in dev.
rmarren1 Oct 2, 2018
015674e
Move component validation to its own method.
rmarren1 Oct 2, 2018
8c2d97f
Move initial layout test, add initialization in callback test
rmarren1 Oct 2, 2018
9fcfa96
Change name of initialization validation error
rmarren1 Oct 2, 2018
95f20cd
Add callback component initialization validation
rmarren1 Oct 2, 2018
f92812b
Make sure children is component before validation.
rmarren1 Oct 2, 2018
0a57cc5
Add Cerberus to setup.py install_requires.
rmarren1 Oct 5, 2018
64b4f5c
Give more information in validation error messages.
rmarren1 Oct 5, 2018
0a515d2
` -> * for error message blocks, so you can copy paste to github.
rmarren1 Oct 5, 2018
dce6a06
Rebase
rmarren1 Oct 18, 2018
708c2f7
Un-comment broken test.
rmarren1 Oct 18, 2018
c8f2953
Add test for using boolean in enum
rmarren1 Oct 18, 2018
c64bc6d
Update Table test component for boolean enum values
rmarren1 Oct 18, 2018
8202256
Forgot to add changed metadata_test.py file (Table component)
rmarren1 Oct 18, 2018
e3aa8d9
Add support for boolean in enum to schema generation.
rmarren1 Oct 18, 2018
f9db291
Add a test for 'options_with_unique_values' validator.
rmarren1 Oct 19, 2018
41d0e81
Add 'options_with_unique_values' validator.
rmarren1 Oct 19, 2018
616583a
lines too long fixes.
rmarren1 Oct 19, 2018
588ce3d
pylint fixes
rmarren1 Oct 19, 2018
cead8e7
Rebase
rmarren1 Nov 2, 2018
9962b2a
Change `disable_component_validation` to `suppress_validation_callbacks`
rmarren1 Nov 2, 2018
3bcfefb
Small typo in test react component
rmarren1 Nov 2, 2018
a5093a0
Monkey patch schemas onto dash_html_components for test
rmarren1 Nov 2, 2018
4af81bf
Use sys.modules rather than dynamic import.
rmarren1 Nov 2, 2018
d81fadb
Disable validation exceptions when in production.
rmarren1 Nov 2, 2018
944bcc3
Tell user how to turn off validation exceptions in the message.
rmarren1 Nov 2, 2018
b785e1b
Pylint fixes
rmarren1 Nov 2, 2018
ea5cf00
Fix line too long
rmarren1 Nov 2, 2018
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .circleci/config.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -49,6 +49,7 @@ jobs:
python --version
python -m unittest tests.development.test_base_component
python -m unittest tests.development.test_component_loader
python -m unittest tests.development.test_component_validation
python -m unittest tests.test_integration
python -m unittest tests.test_resources
python -m unittest tests.test_configs
Expand Down
3 changes: 3 additions & 0 deletions .circleci/requirements/dev-requirements-py37.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,8 +9,11 @@ mock
tox
tox-pyenv
six
numpy
pandas
plotly>=2.0.8
requests[security]
flake8
pylint==2.1.1
astroid==2.0.4
Cerberus==1.2
3 changes: 3 additions & 0 deletions .circleci/requirements/dev-requirements.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,7 +10,10 @@ tox
tox-pyenv
mock
six
numpy
pandas
plotly>=2.0.8
requests[security]
flake8
pylint==1.9.2
Cerberus==1.2
1 change: 1 addition & 0 deletions .pylintrc37
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,6 +63,7 @@ confidence=
disable=invalid-name,
missing-docstring,
print-statement,
too-many-lines,
parameter-unpacking,
unpacking-in-except,
old-raise-syntax,
Expand Down
121 changes: 111 additions & 10 deletions dash/dash.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,11 +5,13 @@
import collections
import importlib
import json
import pprint
import pkgutil
import warnings
import re

from functools import wraps
from textwrap import dedent

import plotly
import dash_renderer
Expand All@@ -20,6 +22,8 @@
from .dependencies import Event, Input, Output, State
from .resources import Scripts, Css
from .development.base_component import Component
from .development.validator import (DashValidator,
generate_validation_error_message)
from . import exceptions
from ._utils import AttributeDict as _AttributeDict
from ._utils import interpolate_str as _interpolate
Expand DownExpand Up@@ -84,6 +88,7 @@ def __init__(
external_scripts=None,
external_stylesheets=None,
suppress_callback_exceptions=None,
suppress_validation_exceptions=None,
components_cache_max_age=None,
**kwargs):

Expand DownExpand Up@@ -126,6 +131,10 @@ def __init__(
'suppress_callback_exceptions',
suppress_callback_exceptions, env_configs, False
),
'suppress_validation_exceptions': _configs.get_config(
Comment thread
rmarren1 marked this conversation as resolved.
'suppress_validation_exceptions',
suppress_validation_exceptions, env_configs, False
),
'routes_pathname_prefix': routes_pathname_prefix,
'requests_pathname_prefix': requests_pathname_prefix,
'include_assets_files': _configs.get_config(
Expand DownExpand Up@@ -168,6 +177,7 @@ def _handle_error(error):
self.assets_ignore = assets_ignore

self.registered_paths = {}
self.namespaces = {}

# urls
self.routes = []
Expand DownExpand Up@@ -256,7 +266,6 @@ def layout(self, value):
'a dash component.')

self._layout = value

layout_value = self._layout_value()
# pylint: disable=protected-access
self.css._update_layout(layout_value)
Expand DownExpand Up@@ -575,7 +584,7 @@ def react(self, *args, **kwargs):
'Use `callback` instead. `callback` has a new syntax too, '
'so make sure to call `help(app.callback)` to learn more.')

def _validate_callback(self, output, inputs, state, events):
def _validate_callback_definition(self, output, inputs, state, events):
# pylint: disable=too-many-branches
layout = self._cached_layout or self._layout_value()

Expand DownExpand Up@@ -713,7 +722,7 @@ def _validate_callback(self, output, inputs, state, events):
output.component_id,
output.component_property).replace(' ', ''))

def _validate_callback_output(self, output_value, output):
def _debug_callback_serialization_error(self, output_value, output):
valid = [str, dict, int, float, type(None), Component]

def _raise_invalid(bad_val, outer_val, bad_type, path, index=None,
Expand DownExpand Up@@ -831,7 +840,7 @@ def _validate_value(val, index=None):
# relationships
# pylint: disable=dangerous-default-value
def callback(self, output, inputs=[], state=[], events=[]):
self._validate_callback(output, inputs, state, events)
self._validate_callback_definition(output, inputs, state, events)

callback_id = '{}.{}'.format(
output.component_id, output.component_property
Expand All@@ -853,13 +862,11 @@ def callback(self, output, inputs=[], state=[], events=[]):

def wrap_func(func):
@wraps(func)
def add_context(*args, **kwargs):

output_value = func(*args, **kwargs)
def add_context(validated_output):
response = {
'response': {
'props': {
output.component_property: output_value
output.component_property: validated_output
}
}
}
Expand All@@ -870,7 +877,10 @@ def add_context(*args, **kwargs):
cls=plotly.utils.PlotlyJSONEncoder
)
except TypeError:
self._validate_callback_output(output_value, output)
self._debug_callback_serialization_error(
validated_output,
output
)
raise exceptions.InvalidCallbackReturnValue('''
The callback for property `{property:s}`
of component `{id:s}` returned a value
Expand All@@ -887,6 +897,7 @@ def add_context(*args, **kwargs):
mimetype='application/json'
)

self.callback_map[callback_id]['func'] = func
self.callback_map[callback_id]['callback'] = add_context

return add_context
Expand DownExpand Up@@ -915,7 +926,88 @@ def dispatch(self):
c['id'] == component_registration['id']
][0])

return self.callback_map[target_id]['callback'](*args)
output_value = self.callback_map[target_id]['func'](*args)

# Only validate if we get required information from renderer
# and validation is not turned off by user
if (
(not self.config.suppress_validation_exceptions) and
Comment thread
rmarren1 marked this conversation as resolved.
'namespace' in output and
'type' in output
):
# Python2.7 might make these keys and values unicode
namespace = str(output['namespace'])
component_type = str(output['type'])
component_id = str(output['id'])
component_property = str(output['property'])
callback_func_name = self.callback_map[target_id]['func'].__name__
self._validate_callback_output(namespace, component_type,
component_id, component_property,
callback_func_name,
args, output_value)

return self.callback_map[target_id]['callback'](output_value)

def _validate_callback_output(self, namespace, component_type,
component_id, component_property,
callback_func_name, args, value):
module = sys.modules[namespace]
Comment thread
rmarren1 marked this conversation as resolved.
component = getattr(module, component_type)
# pylint: disable=protected-access
validator = DashValidator({
component_property: component._schema.get(component_property, {})
})
valid = validator.validate({component_property: value})
if not valid:
error_message = dedent("""\

A Dash Callback produced an invalid value!

Dash tried to update the `{component_property}` prop of the
`{component_name}` with id `{component_id}` by calling the
`{callback_func_name}` function with `{args}` as arguments.

This function call returned `{value}`, which did not pass
validation tests for the `{component_name}` component.

The expected schema for the `{component_property}` prop of the
`{component_name}` component is:

***************************************************************
{component_schema}
***************************************************************

The errors in validation are as follows:

""").format(
component_property=component_property,
component_name=component.__name__,
component_id=component_id,
callback_func_name=callback_func_name,
args='({})'.format(", ".join(map(repr, args))),
value=value,
component_schema=pprint.pformat(
component._schema[component_property]
)
)

error_message = generate_validation_error_message(
validator.errors,
0,
error_message
) + dedent("""
You can turn off these validation exceptions by setting
`app.config.suppress_validation_exceptions=True`
Comment thread
rmarren1 marked this conversation as resolved.
""")

raise exceptions.CallbackOutputValidationError(error_message)
# Must also validate initialization of newly created components
if component_property == 'children':
if isinstance(value, Component):
value.validate()
for component in value.traverse():
if isinstance(component, Component):
component.validate()

def _validate_layout(self):
if self.layout is None:
Expand All@@ -932,6 +1024,11 @@ def _validate_layout(self):

component_ids = {layout_id} if layout_id else set()
for component in to_validate.traverse():
if (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Normally there is no () after if in python.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how else to style since the if statement is > 80 characters. PEP isn't super specific about what to do here: https://www.python.org/dev/peps/pep-0008/#multiline-if-statements.

not self.config.suppress_validation_exceptions and
isinstance(component, Component)
):
component.validate()
component_id = getattr(component, 'id', None)
if component_id and component_id in component_ids:
raise exceptions.DuplicateIdError(
Expand DownExpand Up@@ -1057,5 +1154,9 @@ def run_server(self,
:return:
"""
debug = self.enable_dev_tools(debug, dev_tools_serve_dev_bundles)
if not debug:
# Do not throw debugging exceptions in production.
self.config.suppress_validation_exceptions = True
self.config.suppress_callback_exceptions = True
self.server.run(port=port, debug=debug,
**flask_run_options)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
96 commits
Select commit Hold shift + click to select a range
49d8c21
Update layout on server with each callback, for ids in initial layout.
rmarren1 Aug 15, 2018
12dc611
Update layout for dynamically created elements with ids.
rmarren1 Aug 15, 2018
a0e2f4f
Cerberus validation of initial layout.
rmarren1 Aug 16, 2018
7eb0dbd
Recursive schema generation, schema test case.
rmarren1 Aug 18, 2018
a3ccd76
Custom validation
rmarren1 Aug 23, 2018
377ec7b
Fix validation import
rmarren1 Aug 23, 2018
ce2a255
Merge branch 'master' into validate
rmarren1 Aug 26, 2018
9d0fa01
Make test cases pass
rmarren1 Aug 26, 2018
5665fa4
Fix pylint errors
rmarren1 Aug 26, 2018
f88b068
iteritems -> items for python3 compatibility.
rmarren1 Aug 26, 2018
6205742
Fix unicode and ordering issues with oyaml.
rmarren1 Aug 27, 2018
6b65a67
use dash-renderer version with namespace and type
rmarren1 Aug 27, 2018
4df2bb8
Only validate if 'namespace' and 'type' in json body.
rmarren1 Aug 27, 2018
9e5aa93
Change loader back to json, add hook to transform unicode to string.
rmarren1 Aug 28, 2018
b045753
Do not try to match schema string exactly.
rmarren1 Aug 28, 2018
89d7137
Component validation test cases
rmarren1 Aug 29, 2018
ffd63ba
Required prop type test case
rmarren1 Aug 29, 2018
954aae3
Pylint fixes
rmarren1 Aug 29, 2018
93d4bf6
Fix dict
rmarren1 Aug 29, 2018
a934c26
Improve error message, custom exceptions.
rmarren1 Aug 29, 2018
4bb97ef
Figure validation
rmarren1 Aug 30, 2018
4cb76fe
Fix import order for Pylint.
rmarren1 Aug 30, 2018
233c145
Extra newlines in exceptions for Pylint.
rmarren1 Aug 30, 2018
cf47627
Rename exceptions import for Pylint.
rmarren1 Aug 30, 2018
2817398
Only validate against callback property.
rmarren1 Aug 30, 2018
ee3d1ab
Allow 'None' in children lists.
rmarren1 Aug 30, 2018
9240436
If prop doesn't exist in schema, don't validate callback (for wildcards)
rmarren1 Aug 30, 2018
1373fc2
Fix tests.
rmarren1 Aug 30, 2018
7e804d0
Fix Pylint.
rmarren1 Aug 30, 2018
bc947e6
Add Plotly Figure validation correctly, print error from Plotly.py
rmarren1 Aug 30, 2018
c9b693b
Update renderer requirement
rmarren1 Aug 30, 2018
6c37980
Workaround for PropTypes.null
rmarren1 Sep 2, 2018
fa74afd
Allow 'None' in children arrays.
rmarren1 Sep 3, 2018
5bcec21
Merge branch 'master' into validate
rmarren1 Sep 3, 2018
dd13a80
Fix test cases
rmarren1 Sep 3, 2018
0a33769
Bump dash-html-components version to version published from 3.7.
rmarren1 Sep 5, 2018
c42c3d5
Update integration tests.
rmarren1 Sep 5, 2018
19910ad
Try not installing virtualenv
rmarren1 Sep 6, 2018
4b02ddb
Try venv in home directory
rmarren1 Sep 6, 2018
fcbebd9
Update plotly figure validator.
rmarren1 Sep 7, 2018
54558fe
Bump version and fix pylint
rmarren1 Sep 7, 2018
603aac2
Bump core component versions.
rmarren1 Sep 7, 2018
f6ecaa7
'{}' is not a valid figure.
rmarren1 Sep 7, 2018
5d7625a
Fix figure validator and bump dash-core-components version.
rmarren1 Sep 7, 2018
357ee94
Update wildcard callback test.
rmarren1 Sep 7, 2018
f067f91
Merge branch 'master' into validate
rmarren1 Sep 7, 2018
9b5b9f2
Add Cerberus to dev requirements files
rmarren1 Sep 7, 2018
f6c15da
Allow for required `children`.
rmarren1 Sep 20, 2018
f99490f
Pylint fixes
rmarren1 Sep 21, 2018
886c83a
Merge branch 'master' into validate
rmarren1 Sep 21, 2018
e75d6f1
Fix circle
rmarren1 Sep 21, 2018
8d1727e
Ignore too-many-lines
rmarren1 Sep 21, 2018
87db60a
disable too many lines in .pylintrc
rmarren1 Sep 21, 2018
6967dad
too many lines in .pylint37 too
rmarren1 Sep 21, 2018
42fab98
Add tests for numpy ndarray / pandas series as list.
rmarren1 Sep 28, 2018
06682d2
Update list validator to work for pd.Series, np.ndarray
rmarren1 Sep 28, 2018
906e7c9
Add tests for int / float in enum.
rmarren1 Sep 28, 2018
03a7c08
Update enum to work with int / float
rmarren1 Sep 28, 2018
b1d1337
Add tests for numpy int / float
rmarren1 Sep 28, 2018
426e4f3
Update number validation to support numpy int / float
rmarren1 Sep 28, 2018
b0b5385
Change name `_validate_callback` -> `_validate_callback_definition`
rmarren1 Oct 1, 2018
d98a1a7
`_validate_callback_output` -> `_validate_callback_serialization_error`
rmarren1 Oct 1, 2018
0523beb
Add initial layout validation test.
rmarren1 Oct 1, 2018
b5b7935
Move validation to method in base component.
rmarren1 Oct 1, 2018
d8eb35f
Add disable_component_validation config option.
rmarren1 Oct 1, 2018
b8e2c67
Run component validation on initial layout.
rmarren1 Oct 1, 2018
0fd11b7
Update initial layout validation test.
rmarren1 Oct 1, 2018
2049dfb
Add callback output validation test.
rmarren1 Oct 2, 2018
a3d1402
Bump dash-html-component version in dev.
rmarren1 Oct 2, 2018
015674e
Move component validation to its own method.
rmarren1 Oct 2, 2018
8c2d97f
Move initial layout test, add initialization in callback test
rmarren1 Oct 2, 2018
9fcfa96
Change name of initialization validation error
rmarren1 Oct 2, 2018
95f20cd
Add callback component initialization validation
rmarren1 Oct 2, 2018
f92812b
Make sure children is component before validation.
rmarren1 Oct 2, 2018
0a57cc5
Add Cerberus to setup.py install_requires.
rmarren1 Oct 5, 2018
64b4f5c
Give more information in validation error messages.
rmarren1 Oct 5, 2018
0a515d2
` -> * for error message blocks, so you can copy paste to github.
rmarren1 Oct 5, 2018
dce6a06
Rebase
rmarren1 Oct 18, 2018
708c2f7
Un-comment broken test.
rmarren1 Oct 18, 2018
c8f2953
Add test for using boolean in enum
rmarren1 Oct 18, 2018
c64bc6d
Update Table test component for boolean enum values
rmarren1 Oct 18, 2018
8202256
Forgot to add changed metadata_test.py file (Table component)
rmarren1 Oct 18, 2018
e3aa8d9
Add support for boolean in enum to schema generation.
rmarren1 Oct 18, 2018
f9db291
Add a test for 'options_with_unique_values' validator.
rmarren1 Oct 19, 2018
41d0e81
Add 'options_with_unique_values' validator.
rmarren1 Oct 19, 2018
616583a
lines too long fixes.
rmarren1 Oct 19, 2018
588ce3d
pylint fixes
rmarren1 Oct 19, 2018
cead8e7
Rebase
rmarren1 Nov 2, 2018
9962b2a
Change `disable_component_validation` to `suppress_validation_callbacks`
rmarren1 Nov 2, 2018
3bcfefb
Small typo in test react component
rmarren1 Nov 2, 2018
a5093a0
Monkey patch schemas onto dash_html_components for test
rmarren1 Nov 2, 2018
4af81bf
Use sys.modules rather than dynamic import.
rmarren1 Nov 2, 2018
d81fadb
Disable validation exceptions when in production.
rmarren1 Nov 2, 2018
944bcc3
Tell user how to turn off validation exceptions in the message.
rmarren1 Nov 2, 2018
b785e1b
Pylint fixes
rmarren1 Nov 2, 2018
ea5cf00
Fix line too long
rmarren1 Nov 2, 2018
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .circleci/config.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -49,6 +49,7 @@ jobs:
python --version
python -m unittest tests.development.test_base_component
python -m unittest tests.development.test_component_loader
python -m unittest tests.development.test_component_validation
python -m unittest tests.test_integration
python -m unittest tests.test_resources
python -m unittest tests.test_configs
Expand Down
3 changes: 3 additions & 0 deletions .circleci/requirements/dev-requirements-py37.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,8 +9,11 @@ mock
tox
tox-pyenv
six
numpy
pandas
plotly>=2.0.8
requests[security]
flake8
pylint==2.1.1
astroid==2.0.4
Cerberus==1.2
3 changes: 3 additions & 0 deletions .circleci/requirements/dev-requirements.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,7 +10,10 @@ tox
tox-pyenv
mock
six
numpy
pandas
plotly>=2.0.8
requests[security]
flake8
pylint==1.9.2
Cerberus==1.2
1 change: 1 addition & 0 deletions .pylintrc37
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,6 +63,7 @@ confidence=
disable=invalid-name,
missing-docstring,
print-statement,
too-many-lines,
parameter-unpacking,
unpacking-in-except,
old-raise-syntax,
Expand Down
121 changes: 111 additions & 10 deletions dash/dash.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,11 +5,13 @@
import collections
import importlib
import json
import pprint
import pkgutil
import warnings
import re

from functools import wraps
from textwrap import dedent

import plotly
import dash_renderer
Expand All@@ -20,6 +22,8 @@
from .dependencies import Event, Input, Output, State
from .resources import Scripts, Css
from .development.base_component import Component
from .development.validator import (DashValidator,
generate_validation_error_message)
from . import exceptions
from ._utils import AttributeDict as _AttributeDict
from ._utils import interpolate_str as _interpolate
Expand DownExpand Up@@ -84,6 +88,7 @@ def __init__(
external_scripts=None,
external_stylesheets=None,
suppress_callback_exceptions=None,
suppress_validation_exceptions=None,
components_cache_max_age=None,
**kwargs):

Expand DownExpand Up@@ -126,6 +131,10 @@ def __init__(
'suppress_callback_exceptions',
suppress_callback_exceptions, env_configs, False
),
'suppress_validation_exceptions': _configs.get_config(
Comment thread
rmarren1 marked this conversation as resolved.
'suppress_validation_exceptions',
suppress_validation_exceptions, env_configs, False
),
'routes_pathname_prefix': routes_pathname_prefix,
'requests_pathname_prefix': requests_pathname_prefix,
'include_assets_files': _configs.get_config(
Expand DownExpand Up@@ -168,6 +177,7 @@ def _handle_error(error):
self.assets_ignore = assets_ignore

self.registered_paths = {}
self.namespaces = {}

# urls
self.routes = []
Expand DownExpand Up@@ -256,7 +266,6 @@ def layout(self, value):
'a dash component.')

self._layout = value

layout_value = self._layout_value()
# pylint: disable=protected-access
self.css._update_layout(layout_value)
Expand DownExpand Up@@ -575,7 +584,7 @@ def react(self, *args, **kwargs):
'Use `callback` instead. `callback` has a new syntax too, '
'so make sure to call `help(app.callback)` to learn more.')

def _validate_callback(self, output, inputs, state, events):
def _validate_callback_definition(self, output, inputs, state, events):
# pylint: disable=too-many-branches
layout = self._cached_layout or self._layout_value()

Expand DownExpand Up@@ -713,7 +722,7 @@ def _validate_callback(self, output, inputs, state, events):
output.component_id,
output.component_property).replace(' ', ''))

def _validate_callback_output(self, output_value, output):
def _debug_callback_serialization_error(self, output_value, output):
valid = [str, dict, int, float, type(None), Component]

def _raise_invalid(bad_val, outer_val, bad_type, path, index=None,
Expand DownExpand Up@@ -831,7 +840,7 @@ def _validate_value(val, index=None):
# relationships
# pylint: disable=dangerous-default-value
def callback(self, output, inputs=[], state=[], events=[]):
self._validate_callback(output, inputs, state, events)
self._validate_callback_definition(output, inputs, state, events)

callback_id = '{}.{}'.format(
output.component_id, output.component_property
Expand All@@ -853,13 +862,11 @@ def callback(self, output, inputs=[], state=[], events=[]):

def wrap_func(func):
@wraps(func)
def add_context(*args, **kwargs):

output_value = func(*args, **kwargs)
def add_context(validated_output):
response = {
'response': {
'props': {
output.component_property: output_value
output.component_property: validated_output
}
}
}
Expand All@@ -870,7 +877,10 @@ def add_context(*args, **kwargs):
cls=plotly.utils.PlotlyJSONEncoder
)
except TypeError:
self._validate_callback_output(output_value, output)
self._debug_callback_serialization_error(
validated_output,
output
)
raise exceptions.InvalidCallbackReturnValue('''
The callback for property `{property:s}`
of component `{id:s}` returned a value
Expand All@@ -887,6 +897,7 @@ def add_context(*args, **kwargs):
mimetype='application/json'
)

self.callback_map[callback_id]['func'] = func
self.callback_map[callback_id]['callback'] = add_context

return add_context
Expand DownExpand Up@@ -915,7 +926,88 @@ def dispatch(self):
c['id'] == component_registration['id']
][0])

return self.callback_map[target_id]['callback'](*args)
output_value = self.callback_map[target_id]['func'](*args)

# Only validate if we get required information from renderer
# and validation is not turned off by user
if (
(not self.config.suppress_validation_exceptions) and
Comment thread
rmarren1 marked this conversation as resolved.
'namespace' in output and
'type' in output
):
# Python2.7 might make these keys and values unicode
namespace = str(output['namespace'])
component_type = str(output['type'])
component_id = str(output['id'])
component_property = str(output['property'])
callback_func_name = self.callback_map[target_id]['func'].__name__
self._validate_callback_output(namespace, component_type,
component_id, component_property,
callback_func_name,
args, output_value)

return self.callback_map[target_id]['callback'](output_value)

def _validate_callback_output(self, namespace, component_type,
component_id, component_property,
callback_func_name, args, value):
module = sys.modules[namespace]
Comment thread
rmarren1 marked this conversation as resolved.
component = getattr(module, component_type)
# pylint: disable=protected-access
validator = DashValidator({
component_property: component._schema.get(component_property, {})
})
valid = validator.validate({component_property: value})
if not valid:
error_message = dedent("""\

A Dash Callback produced an invalid value!

Dash tried to update the `{component_property}` prop of the
`{component_name}` with id `{component_id}` by calling the
`{callback_func_name}` function with `{args}` as arguments.

This function call returned `{value}`, which did not pass
validation tests for the `{component_name}` component.

The expected schema for the `{component_property}` prop of the
`{component_name}` component is:

***************************************************************
{component_schema}
***************************************************************

The errors in validation are as follows:

""").format(
component_property=component_property,
component_name=component.__name__,
component_id=component_id,
callback_func_name=callback_func_name,
args='({})'.format(", ".join(map(repr, args))),
value=value,
component_schema=pprint.pformat(
component._schema[component_property]
)
)

error_message = generate_validation_error_message(
validator.errors,
0,
error_message
) + dedent("""
You can turn off these validation exceptions by setting
`app.config.suppress_validation_exceptions=True`
Comment thread
rmarren1 marked this conversation as resolved.
""")

raise exceptions.CallbackOutputValidationError(error_message)
# Must also validate initialization of newly created components
if component_property == 'children':
if isinstance(value, Component):
value.validate()
for component in value.traverse():
if isinstance(component, Component):
component.validate()

def _validate_layout(self):
if self.layout is None:
Expand All@@ -932,6 +1024,11 @@ def _validate_layout(self):

component_ids = {layout_id} if layout_id else set()
for component in to_validate.traverse():
if (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Normally there is no () after if in python.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how else to style since the if statement is > 80 characters. PEP isn't super specific about what to do here: https://www.python.org/dev/peps/pep-0008/#multiline-if-statements.

not self.config.suppress_validation_exceptions and
isinstance(component, Component)
):
component.validate()
component_id = getattr(component, 'id', None)
if component_id and component_id in component_ids:
raise exceptions.DuplicateIdError(
Expand DownExpand Up@@ -1057,5 +1154,9 @@ def run_server(self,
:return:
"""
debug = self.enable_dev_tools(debug, dev_tools_serve_dev_bundles)
if not debug:
# Do not throw debugging exceptions in production.
self.config.suppress_validation_exceptions = True
self.config.suppress_callback_exceptions = True
self.server.run(port=port, debug=debug,
**flask_run_options)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
96 commits
Select commit Hold shift + click to select a range
49d8c21
Update layout on server with each callback, for ids in initial layout.
rmarren1 Aug 15, 2018
12dc611
Update layout for dynamically created elements with ids.
rmarren1 Aug 15, 2018
a0e2f4f
Cerberus validation of initial layout.
rmarren1 Aug 16, 2018
7eb0dbd
Recursive schema generation, schema test case.
rmarren1 Aug 18, 2018
a3ccd76
Custom validation
rmarren1 Aug 23, 2018
377ec7b
Fix validation import
rmarren1 Aug 23, 2018
ce2a255
Merge branch 'master' into validate
rmarren1 Aug 26, 2018
9d0fa01
Make test cases pass
rmarren1 Aug 26, 2018
5665fa4
Fix pylint errors
rmarren1 Aug 26, 2018
f88b068
iteritems -> items for python3 compatibility.
rmarren1 Aug 26, 2018
6205742
Fix unicode and ordering issues with oyaml.
rmarren1 Aug 27, 2018
6b65a67
use dash-renderer version with namespace and type
rmarren1 Aug 27, 2018
4df2bb8
Only validate if 'namespace' and 'type' in json body.
rmarren1 Aug 27, 2018
9e5aa93
Change loader back to json, add hook to transform unicode to string.
rmarren1 Aug 28, 2018
b045753
Do not try to match schema string exactly.
rmarren1 Aug 28, 2018
89d7137
Component validation test cases
rmarren1 Aug 29, 2018
ffd63ba
Required prop type test case
rmarren1 Aug 29, 2018
954aae3
Pylint fixes
rmarren1 Aug 29, 2018
93d4bf6
Fix dict
rmarren1 Aug 29, 2018
a934c26
Improve error message, custom exceptions.
rmarren1 Aug 29, 2018
4bb97ef
Figure validation
rmarren1 Aug 30, 2018
4cb76fe
Fix import order for Pylint.
rmarren1 Aug 30, 2018
233c145
Extra newlines in exceptions for Pylint.
rmarren1 Aug 30, 2018
cf47627
Rename exceptions import for Pylint.
rmarren1 Aug 30, 2018
2817398
Only validate against callback property.
rmarren1 Aug 30, 2018
ee3d1ab
Allow 'None' in children lists.
rmarren1 Aug 30, 2018
9240436
If prop doesn't exist in schema, don't validate callback (for wildcards)
rmarren1 Aug 30, 2018
1373fc2
Fix tests.
rmarren1 Aug 30, 2018
7e804d0
Fix Pylint.
rmarren1 Aug 30, 2018
bc947e6
Add Plotly Figure validation correctly, print error from Plotly.py
rmarren1 Aug 30, 2018
c9b693b
Update renderer requirement
rmarren1 Aug 30, 2018
6c37980
Workaround for PropTypes.null
rmarren1 Sep 2, 2018
fa74afd
Allow 'None' in children arrays.
rmarren1 Sep 3, 2018
5bcec21
Merge branch 'master' into validate
rmarren1 Sep 3, 2018
dd13a80
Fix test cases
rmarren1 Sep 3, 2018
0a33769
Bump dash-html-components version to version published from 3.7.
rmarren1 Sep 5, 2018
c42c3d5
Update integration tests.
rmarren1 Sep 5, 2018
19910ad
Try not installing virtualenv
rmarren1 Sep 6, 2018
4b02ddb
Try venv in home directory
rmarren1 Sep 6, 2018
fcbebd9
Update plotly figure validator.
rmarren1 Sep 7, 2018
54558fe
Bump version and fix pylint
rmarren1 Sep 7, 2018
603aac2
Bump core component versions.
rmarren1 Sep 7, 2018
f6ecaa7
'{}' is not a valid figure.
rmarren1 Sep 7, 2018
5d7625a
Fix figure validator and bump dash-core-components version.
rmarren1 Sep 7, 2018
357ee94
Update wildcard callback test.
rmarren1 Sep 7, 2018
f067f91
Merge branch 'master' into validate
rmarren1 Sep 7, 2018
9b5b9f2
Add Cerberus to dev requirements files
rmarren1 Sep 7, 2018
f6c15da
Allow for required `children`.
rmarren1 Sep 20, 2018
f99490f
Pylint fixes
rmarren1 Sep 21, 2018
886c83a
Merge branch 'master' into validate
rmarren1 Sep 21, 2018
e75d6f1
Fix circle
rmarren1 Sep 21, 2018
8d1727e
Ignore too-many-lines
rmarren1 Sep 21, 2018
87db60a
disable too many lines in .pylintrc
rmarren1 Sep 21, 2018
6967dad
too many lines in .pylint37 too
rmarren1 Sep 21, 2018
42fab98
Add tests for numpy ndarray / pandas series as list.
rmarren1 Sep 28, 2018
06682d2
Update list validator to work for pd.Series, np.ndarray
rmarren1 Sep 28, 2018
906e7c9
Add tests for int / float in enum.
rmarren1 Sep 28, 2018
03a7c08
Update enum to work with int / float
rmarren1 Sep 28, 2018
b1d1337
Add tests for numpy int / float
rmarren1 Sep 28, 2018
426e4f3
Update number validation to support numpy int / float
rmarren1 Sep 28, 2018
b0b5385
Change name `_validate_callback` -> `_validate_callback_definition`
rmarren1 Oct 1, 2018
d98a1a7
`_validate_callback_output` -> `_validate_callback_serialization_error`
rmarren1 Oct 1, 2018
0523beb
Add initial layout validation test.
rmarren1 Oct 1, 2018
b5b7935
Move validation to method in base component.
rmarren1 Oct 1, 2018
d8eb35f
Add disable_component_validation config option.
rmarren1 Oct 1, 2018
b8e2c67
Run component validation on initial layout.
rmarren1 Oct 1, 2018
0fd11b7
Update initial layout validation test.
rmarren1 Oct 1, 2018
2049dfb
Add callback output validation test.
rmarren1 Oct 2, 2018
a3d1402
Bump dash-html-component version in dev.
rmarren1 Oct 2, 2018
015674e
Move component validation to its own method.
rmarren1 Oct 2, 2018
8c2d97f
Move initial layout test, add initialization in callback test
rmarren1 Oct 2, 2018
9fcfa96
Change name of initialization validation error
rmarren1 Oct 2, 2018
95f20cd
Add callback component initialization validation
rmarren1 Oct 2, 2018
f92812b
Make sure children is component before validation.
rmarren1 Oct 2, 2018
0a57cc5
Add Cerberus to setup.py install_requires.
rmarren1 Oct 5, 2018
64b4f5c
Give more information in validation error messages.
rmarren1 Oct 5, 2018
0a515d2
` -> * for error message blocks, so you can copy paste to github.
rmarren1 Oct 5, 2018
dce6a06
Rebase
rmarren1 Oct 18, 2018
708c2f7
Un-comment broken test.
rmarren1 Oct 18, 2018
c8f2953
Add test for using boolean in enum
rmarren1 Oct 18, 2018
c64bc6d
Update Table test component for boolean enum values
rmarren1 Oct 18, 2018
8202256
Forgot to add changed metadata_test.py file (Table component)
rmarren1 Oct 18, 2018
e3aa8d9
Add support for boolean in enum to schema generation.
rmarren1 Oct 18, 2018
f9db291
Add a test for 'options_with_unique_values' validator.
rmarren1 Oct 19, 2018
41d0e81
Add 'options_with_unique_values' validator.
rmarren1 Oct 19, 2018
616583a
lines too long fixes.
rmarren1 Oct 19, 2018
588ce3d
pylint fixes
rmarren1 Oct 19, 2018
cead8e7
Rebase
rmarren1 Nov 2, 2018
9962b2a
Change `disable_component_validation` to `suppress_validation_callbacks`
rmarren1 Nov 2, 2018
3bcfefb
Small typo in test react component
rmarren1 Nov 2, 2018
a5093a0
Monkey patch schemas onto dash_html_components for test
rmarren1 Nov 2, 2018
4af81bf
Use sys.modules rather than dynamic import.
rmarren1 Nov 2, 2018
d81fadb
Disable validation exceptions when in production.
rmarren1 Nov 2, 2018
944bcc3
Tell user how to turn off validation exceptions in the message.
rmarren1 Nov 2, 2018
b785e1b
Pylint fixes
rmarren1 Nov 2, 2018
ea5cf00
Fix line too long
rmarren1 Nov 2, 2018
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .circleci/config.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -49,6 +49,7 @@ jobs:
python --version
python -m unittest tests.development.test_base_component
python -m unittest tests.development.test_component_loader
python -m unittest tests.development.test_component_validation
python -m unittest tests.test_integration
python -m unittest tests.test_resources
python -m unittest tests.test_configs
Expand Down
3 changes: 3 additions & 0 deletions .circleci/requirements/dev-requirements-py37.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,8 +9,11 @@ mock
tox
tox-pyenv
six
numpy
pandas
plotly>=2.0.8
requests[security]
flake8
pylint==2.1.1
astroid==2.0.4
Cerberus==1.2
3 changes: 3 additions & 0 deletions .circleci/requirements/dev-requirements.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,7 +10,10 @@ tox
tox-pyenv
mock
six
numpy
pandas
plotly>=2.0.8
requests[security]
flake8
pylint==1.9.2
Cerberus==1.2
1 change: 1 addition & 0 deletions .pylintrc37
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,6 +63,7 @@ confidence=
disable=invalid-name,
missing-docstring,
print-statement,
too-many-lines,
parameter-unpacking,
unpacking-in-except,
old-raise-syntax,
Expand Down
121 changes: 111 additions & 10 deletions dash/dash.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,11 +5,13 @@
import collections
import importlib
import json
import pprint
import pkgutil
import warnings
import re

from functools import wraps
from textwrap import dedent

import plotly
import dash_renderer
Expand All@@ -20,6 +22,8 @@
from .dependencies import Event, Input, Output, State
from .resources import Scripts, Css
from .development.base_component import Component
from .development.validator import (DashValidator,
generate_validation_error_message)
from . import exceptions
from ._utils import AttributeDict as _AttributeDict
from ._utils import interpolate_str as _interpolate
Expand DownExpand Up@@ -84,6 +88,7 @@ def __init__(
external_scripts=None,
external_stylesheets=None,
suppress_callback_exceptions=None,
suppress_validation_exceptions=None,
components_cache_max_age=None,
**kwargs):

Expand DownExpand Up@@ -126,6 +131,10 @@ def __init__(
'suppress_callback_exceptions',
suppress_callback_exceptions, env_configs, False
),
'suppress_validation_exceptions': _configs.get_config(
Comment thread
rmarren1 marked this conversation as resolved.
'suppress_validation_exceptions',
suppress_validation_exceptions, env_configs, False
),
'routes_pathname_prefix': routes_pathname_prefix,
'requests_pathname_prefix': requests_pathname_prefix,
'include_assets_files': _configs.get_config(
Expand DownExpand Up@@ -168,6 +177,7 @@ def _handle_error(error):
self.assets_ignore = assets_ignore

self.registered_paths = {}
self.namespaces = {}

# urls
self.routes = []
Expand DownExpand Up@@ -256,7 +266,6 @@ def layout(self, value):
'a dash component.')

self._layout = value

layout_value = self._layout_value()
# pylint: disable=protected-access
self.css._update_layout(layout_value)
Expand DownExpand Up@@ -575,7 +584,7 @@ def react(self, *args, **kwargs):
'Use `callback` instead. `callback` has a new syntax too, '
'so make sure to call `help(app.callback)` to learn more.')

def _validate_callback(self, output, inputs, state, events):
def _validate_callback_definition(self, output, inputs, state, events):
# pylint: disable=too-many-branches
layout = self._cached_layout or self._layout_value()

Expand DownExpand Up@@ -713,7 +722,7 @@ def _validate_callback(self, output, inputs, state, events):
output.component_id,
output.component_property).replace(' ', ''))

def _validate_callback_output(self, output_value, output):
def _debug_callback_serialization_error(self, output_value, output):
valid = [str, dict, int, float, type(None), Component]

def _raise_invalid(bad_val, outer_val, bad_type, path, index=None,
Expand DownExpand Up@@ -831,7 +840,7 @@ def _validate_value(val, index=None):
# relationships
# pylint: disable=dangerous-default-value
def callback(self, output, inputs=[], state=[], events=[]):
self._validate_callback(output, inputs, state, events)
self._validate_callback_definition(output, inputs, state, events)

callback_id = '{}.{}'.format(
output.component_id, output.component_property
Expand All@@ -853,13 +862,11 @@ def callback(self, output, inputs=[], state=[], events=[]):

def wrap_func(func):
@wraps(func)
def add_context(*args, **kwargs):

output_value = func(*args, **kwargs)
def add_context(validated_output):
response = {
'response': {
'props': {
output.component_property: output_value
output.component_property: validated_output
}
}
}
Expand All@@ -870,7 +877,10 @@ def add_context(*args, **kwargs):
cls=plotly.utils.PlotlyJSONEncoder
)
except TypeError:
self._validate_callback_output(output_value, output)
self._debug_callback_serialization_error(
validated_output,
output
)
raise exceptions.InvalidCallbackReturnValue('''
The callback for property `{property:s}`
of component `{id:s}` returned a value
Expand All@@ -887,6 +897,7 @@ def add_context(*args, **kwargs):
mimetype='application/json'
)

self.callback_map[callback_id]['func'] = func
self.callback_map[callback_id]['callback'] = add_context

return add_context
Expand DownExpand Up@@ -915,7 +926,88 @@ def dispatch(self):
c['id'] == component_registration['id']
][0])

return self.callback_map[target_id]['callback'](*args)
output_value = self.callback_map[target_id]['func'](*args)

# Only validate if we get required information from renderer
# and validation is not turned off by user
if (
(not self.config.suppress_validation_exceptions) and
Comment thread
rmarren1 marked this conversation as resolved.
'namespace' in output and
'type' in output
):
# Python2.7 might make these keys and values unicode
namespace = str(output['namespace'])
component_type = str(output['type'])
component_id = str(output['id'])
component_property = str(output['property'])
callback_func_name = self.callback_map[target_id]['func'].__name__
self._validate_callback_output(namespace, component_type,
component_id, component_property,
callback_func_name,
args, output_value)

return self.callback_map[target_id]['callback'](output_value)

def _validate_callback_output(self, namespace, component_type,
component_id, component_property,
callback_func_name, args, value):
module = sys.modules[namespace]
Comment thread
rmarren1 marked this conversation as resolved.
component = getattr(module, component_type)
# pylint: disable=protected-access
validator = DashValidator({
component_property: component._schema.get(component_property, {})
})
valid = validator.validate({component_property: value})
if not valid:
error_message = dedent("""\

A Dash Callback produced an invalid value!

Dash tried to update the `{component_property}` prop of the
`{component_name}` with id `{component_id}` by calling the
`{callback_func_name}` function with `{args}` as arguments.

This function call returned `{value}`, which did not pass
validation tests for the `{component_name}` component.

The expected schema for the `{component_property}` prop of the
`{component_name}` component is:

***************************************************************
{component_schema}
***************************************************************

The errors in validation are as follows:

""").format(
component_property=component_property,
component_name=component.__name__,
component_id=component_id,
callback_func_name=callback_func_name,
args='({})'.format(", ".join(map(repr, args))),
value=value,
component_schema=pprint.pformat(
component._schema[component_property]
)
)

error_message = generate_validation_error_message(
validator.errors,
0,
error_message
) + dedent("""
You can turn off these validation exceptions by setting
`app.config.suppress_validation_exceptions=True`
Comment thread
rmarren1 marked this conversation as resolved.
""")

raise exceptions.CallbackOutputValidationError(error_message)
# Must also validate initialization of newly created components
if component_property == 'children':
if isinstance(value, Component):
value.validate()
for component in value.traverse():
if isinstance(component, Component):
component.validate()

def _validate_layout(self):
if self.layout is None:
Expand All@@ -932,6 +1024,11 @@ def _validate_layout(self):

component_ids = {layout_id} if layout_id else set()
for component in to_validate.traverse():
if (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Normally there is no () after if in python.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how else to style since the if statement is > 80 characters. PEP isn't super specific about what to do here: https://www.python.org/dev/peps/pep-0008/#multiline-if-statements.

not self.config.suppress_validation_exceptions and
isinstance(component, Component)
):
component.validate()
component_id = getattr(component, 'id', None)
if component_id and component_id in component_ids:
raise exceptions.DuplicateIdError(
Expand DownExpand Up@@ -1057,5 +1154,9 @@ def run_server(self,
:return:
"""
debug = self.enable_dev_tools(debug, dev_tools_serve_dev_bundles)
if not debug:
# Do not throw debugging exceptions in production.
self.config.suppress_validation_exceptions = True
self.config.suppress_callback_exceptions = True
self.server.run(port=port, debug=debug,
**flask_run_options)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
96 commits
Select commit Hold shift + click to select a range
49d8c21
Update layout on server with each callback, for ids in initial layout.
rmarren1 Aug 15, 2018
12dc611
Update layout for dynamically created elements with ids.
rmarren1 Aug 15, 2018
a0e2f4f
Cerberus validation of initial layout.
rmarren1 Aug 16, 2018
7eb0dbd
Recursive schema generation, schema test case.
rmarren1 Aug 18, 2018
a3ccd76
Custom validation
rmarren1 Aug 23, 2018
377ec7b
Fix validation import
rmarren1 Aug 23, 2018
ce2a255
Merge branch 'master' into validate
rmarren1 Aug 26, 2018
9d0fa01
Make test cases pass
rmarren1 Aug 26, 2018
5665fa4
Fix pylint errors
rmarren1 Aug 26, 2018
f88b068
iteritems -> items for python3 compatibility.
rmarren1 Aug 26, 2018
6205742
Fix unicode and ordering issues with oyaml.
rmarren1 Aug 27, 2018
6b65a67
use dash-renderer version with namespace and type
rmarren1 Aug 27, 2018
4df2bb8
Only validate if 'namespace' and 'type' in json body.
rmarren1 Aug 27, 2018
9e5aa93
Change loader back to json, add hook to transform unicode to string.
rmarren1 Aug 28, 2018
b045753
Do not try to match schema string exactly.
rmarren1 Aug 28, 2018
89d7137
Component validation test cases
rmarren1 Aug 29, 2018
ffd63ba
Required prop type test case
rmarren1 Aug 29, 2018
954aae3
Pylint fixes
rmarren1 Aug 29, 2018
93d4bf6
Fix dict
rmarren1 Aug 29, 2018
a934c26
Improve error message, custom exceptions.
rmarren1 Aug 29, 2018
4bb97ef
Figure validation
rmarren1 Aug 30, 2018
4cb76fe
Fix import order for Pylint.
rmarren1 Aug 30, 2018
233c145
Extra newlines in exceptions for Pylint.
rmarren1 Aug 30, 2018
cf47627
Rename exceptions import for Pylint.
rmarren1 Aug 30, 2018
2817398
Only validate against callback property.
rmarren1 Aug 30, 2018
ee3d1ab
Allow 'None' in children lists.
rmarren1 Aug 30, 2018
9240436
If prop doesn't exist in schema, don't validate callback (for wildcards)
rmarren1 Aug 30, 2018
1373fc2
Fix tests.
rmarren1 Aug 30, 2018
7e804d0
Fix Pylint.
rmarren1 Aug 30, 2018
bc947e6
Add Plotly Figure validation correctly, print error from Plotly.py
rmarren1 Aug 30, 2018
c9b693b
Update renderer requirement
rmarren1 Aug 30, 2018
6c37980
Workaround for PropTypes.null
rmarren1 Sep 2, 2018
fa74afd
Allow 'None' in children arrays.
rmarren1 Sep 3, 2018
5bcec21
Merge branch 'master' into validate
rmarren1 Sep 3, 2018
dd13a80
Fix test cases
rmarren1 Sep 3, 2018
0a33769
Bump dash-html-components version to version published from 3.7.
rmarren1 Sep 5, 2018
c42c3d5
Update integration tests.
rmarren1 Sep 5, 2018
19910ad
Try not installing virtualenv
rmarren1 Sep 6, 2018
4b02ddb
Try venv in home directory
rmarren1 Sep 6, 2018
fcbebd9
Update plotly figure validator.
rmarren1 Sep 7, 2018
54558fe
Bump version and fix pylint
rmarren1 Sep 7, 2018
603aac2
Bump core component versions.
rmarren1 Sep 7, 2018
f6ecaa7
'{}' is not a valid figure.
rmarren1 Sep 7, 2018
5d7625a
Fix figure validator and bump dash-core-components version.
rmarren1 Sep 7, 2018
357ee94
Update wildcard callback test.
rmarren1 Sep 7, 2018
f067f91
Merge branch 'master' into validate
rmarren1 Sep 7, 2018
9b5b9f2
Add Cerberus to dev requirements files
rmarren1 Sep 7, 2018
f6c15da
Allow for required `children`.
rmarren1 Sep 20, 2018
f99490f
Pylint fixes
rmarren1 Sep 21, 2018
886c83a
Merge branch 'master' into validate
rmarren1 Sep 21, 2018
e75d6f1
Fix circle
rmarren1 Sep 21, 2018
8d1727e
Ignore too-many-lines
rmarren1 Sep 21, 2018
87db60a
disable too many lines in .pylintrc
rmarren1 Sep 21, 2018
6967dad
too many lines in .pylint37 too
rmarren1 Sep 21, 2018
42fab98
Add tests for numpy ndarray / pandas series as list.
rmarren1 Sep 28, 2018
06682d2
Update list validator to work for pd.Series, np.ndarray
rmarren1 Sep 28, 2018
906e7c9
Add tests for int / float in enum.
rmarren1 Sep 28, 2018
03a7c08
Update enum to work with int / float
rmarren1 Sep 28, 2018
b1d1337
Add tests for numpy int / float
rmarren1 Sep 28, 2018
426e4f3
Update number validation to support numpy int / float
rmarren1 Sep 28, 2018
b0b5385
Change name `_validate_callback` -> `_validate_callback_definition`
rmarren1 Oct 1, 2018
d98a1a7
`_validate_callback_output` -> `_validate_callback_serialization_error`
rmarren1 Oct 1, 2018
0523beb
Add initial layout validation test.
rmarren1 Oct 1, 2018
b5b7935
Move validation to method in base component.
rmarren1 Oct 1, 2018
d8eb35f
Add disable_component_validation config option.
rmarren1 Oct 1, 2018
b8e2c67
Run component validation on initial layout.
rmarren1 Oct 1, 2018
0fd11b7
Update initial layout validation test.
rmarren1 Oct 1, 2018
2049dfb
Add callback output validation test.
rmarren1 Oct 2, 2018
a3d1402
Bump dash-html-component version in dev.
rmarren1 Oct 2, 2018
015674e
Move component validation to its own method.
rmarren1 Oct 2, 2018
8c2d97f
Move initial layout test, add initialization in callback test
rmarren1 Oct 2, 2018
9fcfa96
Change name of initialization validation error
rmarren1 Oct 2, 2018
95f20cd
Add callback component initialization validation
rmarren1 Oct 2, 2018
f92812b
Make sure children is component before validation.
rmarren1 Oct 2, 2018
0a57cc5
Add Cerberus to setup.py install_requires.
rmarren1 Oct 5, 2018
64b4f5c
Give more information in validation error messages.
rmarren1 Oct 5, 2018
0a515d2
` -> * for error message blocks, so you can copy paste to github.
rmarren1 Oct 5, 2018
dce6a06
Rebase
rmarren1 Oct 18, 2018
708c2f7
Un-comment broken test.
rmarren1 Oct 18, 2018
c8f2953
Add test for using boolean in enum
rmarren1 Oct 18, 2018
c64bc6d
Update Table test component for boolean enum values
rmarren1 Oct 18, 2018
8202256
Forgot to add changed metadata_test.py file (Table component)
rmarren1 Oct 18, 2018
e3aa8d9
Add support for boolean in enum to schema generation.
rmarren1 Oct 18, 2018
f9db291
Add a test for 'options_with_unique_values' validator.
rmarren1 Oct 19, 2018
41d0e81
Add 'options_with_unique_values' validator.
rmarren1 Oct 19, 2018
616583a
lines too long fixes.
rmarren1 Oct 19, 2018
588ce3d
pylint fixes
rmarren1 Oct 19, 2018
cead8e7
Rebase
rmarren1 Nov 2, 2018
9962b2a
Change `disable_component_validation` to `suppress_validation_callbacks`
rmarren1 Nov 2, 2018
3bcfefb
Small typo in test react component
rmarren1 Nov 2, 2018
a5093a0
Monkey patch schemas onto dash_html_components for test
rmarren1 Nov 2, 2018
4af81bf
Use sys.modules rather than dynamic import.
rmarren1 Nov 2, 2018
d81fadb
Disable validation exceptions when in production.
rmarren1 Nov 2, 2018
944bcc3
Tell user how to turn off validation exceptions in the message.
rmarren1 Nov 2, 2018
b785e1b
Pylint fixes
rmarren1 Nov 2, 2018
ea5cf00
Fix line too long
rmarren1 Nov 2, 2018
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .circleci/config.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -49,6 +49,7 @@ jobs:
python --version
python -m unittest tests.development.test_base_component
python -m unittest tests.development.test_component_loader
python -m unittest tests.development.test_component_validation
python -m unittest tests.test_integration
python -m unittest tests.test_resources
python -m unittest tests.test_configs
Expand Down
3 changes: 3 additions & 0 deletions .circleci/requirements/dev-requirements-py37.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,8 +9,11 @@ mock
tox
tox-pyenv
six
numpy
pandas
plotly>=2.0.8
requests[security]
flake8
pylint==2.1.1
astroid==2.0.4
Cerberus==1.2
3 changes: 3 additions & 0 deletions .circleci/requirements/dev-requirements.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,7 +10,10 @@ tox
tox-pyenv
mock
six
numpy
pandas
plotly>=2.0.8
requests[security]
flake8
pylint==1.9.2
Cerberus==1.2
1 change: 1 addition & 0 deletions .pylintrc37
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,6 +63,7 @@ confidence=
disable=invalid-name,
missing-docstring,
print-statement,
too-many-lines,
parameter-unpacking,
unpacking-in-except,
old-raise-syntax,
Expand Down
121 changes: 111 additions & 10 deletions dash/dash.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,11 +5,13 @@
import collections
import importlib
import json
import pprint
import pkgutil
import warnings
import re

from functools import wraps
from textwrap import dedent

import plotly
import dash_renderer
Expand All@@ -20,6 +22,8 @@
from .dependencies import Event, Input, Output, State
from .resources import Scripts, Css
from .development.base_component import Component
from .development.validator import (DashValidator,
generate_validation_error_message)
from . import exceptions
from ._utils import AttributeDict as _AttributeDict
from ._utils import interpolate_str as _interpolate
Expand DownExpand Up@@ -84,6 +88,7 @@ def __init__(
external_scripts=None,
external_stylesheets=None,
suppress_callback_exceptions=None,
suppress_validation_exceptions=None,
components_cache_max_age=None,
**kwargs):

Expand DownExpand Up@@ -126,6 +131,10 @@ def __init__(
'suppress_callback_exceptions',
suppress_callback_exceptions, env_configs, False
),
'suppress_validation_exceptions': _configs.get_config(
Comment thread
rmarren1 marked this conversation as resolved.
'suppress_validation_exceptions',
suppress_validation_exceptions, env_configs, False
),
'routes_pathname_prefix': routes_pathname_prefix,
'requests_pathname_prefix': requests_pathname_prefix,
'include_assets_files': _configs.get_config(
Expand DownExpand Up@@ -168,6 +177,7 @@ def _handle_error(error):
self.assets_ignore = assets_ignore

self.registered_paths = {}
self.namespaces = {}

# urls
self.routes = []
Expand DownExpand Up@@ -256,7 +266,6 @@ def layout(self, value):
'a dash component.')

self._layout = value

layout_value = self._layout_value()
# pylint: disable=protected-access
self.css._update_layout(layout_value)
Expand DownExpand Up@@ -575,7 +584,7 @@ def react(self, *args, **kwargs):
'Use `callback` instead. `callback` has a new syntax too, '
'so make sure to call `help(app.callback)` to learn more.')

def _validate_callback(self, output, inputs, state, events):
def _validate_callback_definition(self, output, inputs, state, events):
# pylint: disable=too-many-branches
layout = self._cached_layout or self._layout_value()

Expand DownExpand Up@@ -713,7 +722,7 @@ def _validate_callback(self, output, inputs, state, events):
output.component_id,
output.component_property).replace(' ', ''))

def _validate_callback_output(self, output_value, output):
def _debug_callback_serialization_error(self, output_value, output):
valid = [str, dict, int, float, type(None), Component]

def _raise_invalid(bad_val, outer_val, bad_type, path, index=None,
Expand DownExpand Up@@ -831,7 +840,7 @@ def _validate_value(val, index=None):
# relationships
# pylint: disable=dangerous-default-value
def callback(self, output, inputs=[], state=[], events=[]):
self._validate_callback(output, inputs, state, events)
self._validate_callback_definition(output, inputs, state, events)

callback_id = '{}.{}'.format(
output.component_id, output.component_property
Expand All@@ -853,13 +862,11 @@ def callback(self, output, inputs=[], state=[], events=[]):

def wrap_func(func):
@wraps(func)
def add_context(*args, **kwargs):

output_value = func(*args, **kwargs)
def add_context(validated_output):
response = {
'response': {
'props': {
output.component_property: output_value
output.component_property: validated_output
}
}
}
Expand All@@ -870,7 +877,10 @@ def add_context(*args, **kwargs):
cls=plotly.utils.PlotlyJSONEncoder
)
except TypeError:
self._validate_callback_output(output_value, output)
self._debug_callback_serialization_error(
validated_output,
output
)
raise exceptions.InvalidCallbackReturnValue('''
The callback for property `{property:s}`
of component `{id:s}` returned a value
Expand All@@ -887,6 +897,7 @@ def add_context(*args, **kwargs):
mimetype='application/json'
)

self.callback_map[callback_id]['func'] = func
self.callback_map[callback_id]['callback'] = add_context

return add_context
Expand DownExpand Up@@ -915,7 +926,88 @@ def dispatch(self):
c['id'] == component_registration['id']
][0])

return self.callback_map[target_id]['callback'](*args)
output_value = self.callback_map[target_id]['func'](*args)

# Only validate if we get required information from renderer
# and validation is not turned off by user
if (
(not self.config.suppress_validation_exceptions) and
Comment thread
rmarren1 marked this conversation as resolved.
'namespace' in output and
'type' in output
):
# Python2.7 might make these keys and values unicode
namespace = str(output['namespace'])
component_type = str(output['type'])
component_id = str(output['id'])
component_property = str(output['property'])
callback_func_name = self.callback_map[target_id]['func'].__name__
self._validate_callback_output(namespace, component_type,
component_id, component_property,
callback_func_name,
args, output_value)

return self.callback_map[target_id]['callback'](output_value)

def _validate_callback_output(self, namespace, component_type,
component_id, component_property,
callback_func_name, args, value):
module = sys.modules[namespace]
Comment thread
rmarren1 marked this conversation as resolved.
component = getattr(module, component_type)
# pylint: disable=protected-access
validator = DashValidator({
component_property: component._schema.get(component_property, {})
})
valid = validator.validate({component_property: value})
if not valid:
error_message = dedent("""\

A Dash Callback produced an invalid value!

Dash tried to update the `{component_property}` prop of the
`{component_name}` with id `{component_id}` by calling the
`{callback_func_name}` function with `{args}` as arguments.

This function call returned `{value}`, which did not pass
validation tests for the `{component_name}` component.

The expected schema for the `{component_property}` prop of the
`{component_name}` component is:

***************************************************************
{component_schema}
***************************************************************

The errors in validation are as follows:

""").format(
component_property=component_property,
component_name=component.__name__,
component_id=component_id,
callback_func_name=callback_func_name,
args='({})'.format(", ".join(map(repr, args))),
value=value,
component_schema=pprint.pformat(
component._schema[component_property]
)
)

error_message = generate_validation_error_message(
validator.errors,
0,
error_message
) + dedent("""
You can turn off these validation exceptions by setting
`app.config.suppress_validation_exceptions=True`
Comment thread
rmarren1 marked this conversation as resolved.
""")

raise exceptions.CallbackOutputValidationError(error_message)
# Must also validate initialization of newly created components
if component_property == 'children':
if isinstance(value, Component):
value.validate()
for component in value.traverse():
if isinstance(component, Component):
component.validate()

def _validate_layout(self):
if self.layout is None:
Expand All@@ -932,6 +1024,11 @@ def _validate_layout(self):

component_ids = {layout_id} if layout_id else set()
for component in to_validate.traverse():
if (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Normally there is no () after if in python.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how else to style since the if statement is > 80 characters. PEP isn't super specific about what to do here: https://www.python.org/dev/peps/pep-0008/#multiline-if-statements.

not self.config.suppress_validation_exceptions and
isinstance(component, Component)
):
component.validate()
component_id = getattr(component, 'id', None)
if component_id and component_id in component_ids:
raise exceptions.DuplicateIdError(
Expand DownExpand Up@@ -1057,5 +1154,9 @@ def run_server(self,
:return:
"""
debug = self.enable_dev_tools(debug, dev_tools_serve_dev_bundles)
if not debug:
# Do not throw debugging exceptions in production.
self.config.suppress_validation_exceptions = True
self.config.suppress_callback_exceptions = True
self.server.run(port=port, debug=debug,
**flask_run_options)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
96 commits
Select commit Hold shift + click to select a range
49d8c21
Update layout on server with each callback, for ids in initial layout.
rmarren1 Aug 15, 2018
12dc611
Update layout for dynamically created elements with ids.
rmarren1 Aug 15, 2018
a0e2f4f
Cerberus validation of initial layout.
rmarren1 Aug 16, 2018
7eb0dbd
Recursive schema generation, schema test case.
rmarren1 Aug 18, 2018
a3ccd76
Custom validation
rmarren1 Aug 23, 2018
377ec7b
Fix validation import
rmarren1 Aug 23, 2018
ce2a255
Merge branch 'master' into validate
rmarren1 Aug 26, 2018
9d0fa01
Make test cases pass
rmarren1 Aug 26, 2018
5665fa4
Fix pylint errors
rmarren1 Aug 26, 2018
f88b068
iteritems -> items for python3 compatibility.
rmarren1 Aug 26, 2018
6205742
Fix unicode and ordering issues with oyaml.
rmarren1 Aug 27, 2018
6b65a67
use dash-renderer version with namespace and type
rmarren1 Aug 27, 2018
4df2bb8
Only validate if 'namespace' and 'type' in json body.
rmarren1 Aug 27, 2018
9e5aa93
Change loader back to json, add hook to transform unicode to string.
rmarren1 Aug 28, 2018
b045753
Do not try to match schema string exactly.
rmarren1 Aug 28, 2018
89d7137
Component validation test cases
rmarren1 Aug 29, 2018
ffd63ba
Required prop type test case
rmarren1 Aug 29, 2018
954aae3
Pylint fixes
rmarren1 Aug 29, 2018
93d4bf6
Fix dict
rmarren1 Aug 29, 2018
a934c26
Improve error message, custom exceptions.
rmarren1 Aug 29, 2018
4bb97ef
Figure validation
rmarren1 Aug 30, 2018
4cb76fe
Fix import order for Pylint.
rmarren1 Aug 30, 2018
233c145
Extra newlines in exceptions for Pylint.
rmarren1 Aug 30, 2018
cf47627
Rename exceptions import for Pylint.
rmarren1 Aug 30, 2018
2817398
Only validate against callback property.
rmarren1 Aug 30, 2018
ee3d1ab
Allow 'None' in children lists.
rmarren1 Aug 30, 2018
9240436
If prop doesn't exist in schema, don't validate callback (for wildcards)
rmarren1 Aug 30, 2018
1373fc2
Fix tests.
rmarren1 Aug 30, 2018
7e804d0
Fix Pylint.
rmarren1 Aug 30, 2018
bc947e6
Add Plotly Figure validation correctly, print error from Plotly.py
rmarren1 Aug 30, 2018
c9b693b
Update renderer requirement
rmarren1 Aug 30, 2018
6c37980
Workaround for PropTypes.null
rmarren1 Sep 2, 2018
fa74afd
Allow 'None' in children arrays.
rmarren1 Sep 3, 2018
5bcec21
Merge branch 'master' into validate
rmarren1 Sep 3, 2018
dd13a80
Fix test cases
rmarren1 Sep 3, 2018
0a33769
Bump dash-html-components version to version published from 3.7.
rmarren1 Sep 5, 2018
c42c3d5
Update integration tests.
rmarren1 Sep 5, 2018
19910ad
Try not installing virtualenv
rmarren1 Sep 6, 2018
4b02ddb
Try venv in home directory
rmarren1 Sep 6, 2018
fcbebd9
Update plotly figure validator.
rmarren1 Sep 7, 2018
54558fe
Bump version and fix pylint
rmarren1 Sep 7, 2018
603aac2
Bump core component versions.
rmarren1 Sep 7, 2018
f6ecaa7
'{}' is not a valid figure.
rmarren1 Sep 7, 2018
5d7625a
Fix figure validator and bump dash-core-components version.
rmarren1 Sep 7, 2018
357ee94
Update wildcard callback test.
rmarren1 Sep 7, 2018
f067f91
Merge branch 'master' into validate
rmarren1 Sep 7, 2018
9b5b9f2
Add Cerberus to dev requirements files
rmarren1 Sep 7, 2018
f6c15da
Allow for required `children`.
rmarren1 Sep 20, 2018
f99490f
Pylint fixes
rmarren1 Sep 21, 2018
886c83a
Merge branch 'master' into validate
rmarren1 Sep 21, 2018
e75d6f1
Fix circle
rmarren1 Sep 21, 2018
8d1727e
Ignore too-many-lines
rmarren1 Sep 21, 2018
87db60a
disable too many lines in .pylintrc
rmarren1 Sep 21, 2018
6967dad
too many lines in .pylint37 too
rmarren1 Sep 21, 2018
42fab98
Add tests for numpy ndarray / pandas series as list.
rmarren1 Sep 28, 2018
06682d2
Update list validator to work for pd.Series, np.ndarray
rmarren1 Sep 28, 2018
906e7c9
Add tests for int / float in enum.
rmarren1 Sep 28, 2018
03a7c08
Update enum to work with int / float
rmarren1 Sep 28, 2018
b1d1337
Add tests for numpy int / float
rmarren1 Sep 28, 2018
426e4f3
Update number validation to support numpy int / float
rmarren1 Sep 28, 2018
b0b5385
Change name `_validate_callback` -> `_validate_callback_definition`
rmarren1 Oct 1, 2018
d98a1a7
`_validate_callback_output` -> `_validate_callback_serialization_error`
rmarren1 Oct 1, 2018
0523beb
Add initial layout validation test.
rmarren1 Oct 1, 2018
b5b7935
Move validation to method in base component.
rmarren1 Oct 1, 2018
d8eb35f
Add disable_component_validation config option.
rmarren1 Oct 1, 2018
b8e2c67
Run component validation on initial layout.
rmarren1 Oct 1, 2018
0fd11b7
Update initial layout validation test.
rmarren1 Oct 1, 2018
2049dfb
Add callback output validation test.
rmarren1 Oct 2, 2018
a3d1402
Bump dash-html-component version in dev.
rmarren1 Oct 2, 2018
015674e
Move component validation to its own method.
rmarren1 Oct 2, 2018
8c2d97f
Move initial layout test, add initialization in callback test
rmarren1 Oct 2, 2018
9fcfa96
Change name of initialization validation error
rmarren1 Oct 2, 2018
95f20cd
Add callback component initialization validation
rmarren1 Oct 2, 2018
f92812b
Make sure children is component before validation.
rmarren1 Oct 2, 2018
0a57cc5
Add Cerberus to setup.py install_requires.
rmarren1 Oct 5, 2018
64b4f5c
Give more information in validation error messages.
rmarren1 Oct 5, 2018
0a515d2
` -> * for error message blocks, so you can copy paste to github.
rmarren1 Oct 5, 2018
dce6a06
Rebase
rmarren1 Oct 18, 2018
708c2f7
Un-comment broken test.
rmarren1 Oct 18, 2018
c8f2953
Add test for using boolean in enum
rmarren1 Oct 18, 2018
c64bc6d
Update Table test component for boolean enum values
rmarren1 Oct 18, 2018
8202256
Forgot to add changed metadata_test.py file (Table component)
rmarren1 Oct 18, 2018
e3aa8d9
Add support for boolean in enum to schema generation.
rmarren1 Oct 18, 2018
f9db291
Add a test for 'options_with_unique_values' validator.
rmarren1 Oct 19, 2018
41d0e81
Add 'options_with_unique_values' validator.
rmarren1 Oct 19, 2018
616583a
lines too long fixes.
rmarren1 Oct 19, 2018
588ce3d
pylint fixes
rmarren1 Oct 19, 2018
cead8e7
Rebase
rmarren1 Nov 2, 2018
9962b2a
Change `disable_component_validation` to `suppress_validation_callbacks`
rmarren1 Nov 2, 2018
3bcfefb
Small typo in test react component
rmarren1 Nov 2, 2018
a5093a0
Monkey patch schemas onto dash_html_components for test
rmarren1 Nov 2, 2018
4af81bf
Use sys.modules rather than dynamic import.
rmarren1 Nov 2, 2018
d81fadb
Disable validation exceptions when in production.
rmarren1 Nov 2, 2018
944bcc3
Tell user how to turn off validation exceptions in the message.
rmarren1 Nov 2, 2018
b785e1b
Pylint fixes
rmarren1 Nov 2, 2018
ea5cf00
Fix line too long
rmarren1 Nov 2, 2018
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .circleci/config.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -49,6 +49,7 @@ jobs:
python --version
python -m unittest tests.development.test_base_component
python -m unittest tests.development.test_component_loader
python -m unittest tests.development.test_component_validation
python -m unittest tests.test_integration
python -m unittest tests.test_resources
python -m unittest tests.test_configs
Expand Down
3 changes: 3 additions & 0 deletions .circleci/requirements/dev-requirements-py37.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,8 +9,11 @@ mock
tox
tox-pyenv
six
numpy
pandas
plotly>=2.0.8
requests[security]
flake8
pylint==2.1.1
astroid==2.0.4
Cerberus==1.2
3 changes: 3 additions & 0 deletions .circleci/requirements/dev-requirements.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,7 +10,10 @@ tox
tox-pyenv
mock
six
numpy
pandas
plotly>=2.0.8
requests[security]
flake8
pylint==1.9.2
Cerberus==1.2
1 change: 1 addition & 0 deletions .pylintrc37
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,6 +63,7 @@ confidence=
disable=invalid-name,
missing-docstring,
print-statement,
too-many-lines,
parameter-unpacking,
unpacking-in-except,
old-raise-syntax,
Expand Down
121 changes: 111 additions & 10 deletions dash/dash.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,11 +5,13 @@
import collections
import importlib
import json
import pprint
import pkgutil
import warnings
import re

from functools import wraps
from textwrap import dedent

import plotly
import dash_renderer
Expand All@@ -20,6 +22,8 @@
from .dependencies import Event, Input, Output, State
from .resources import Scripts, Css
from .development.base_component import Component
from .development.validator import (DashValidator,
generate_validation_error_message)
from . import exceptions
from ._utils import AttributeDict as _AttributeDict
from ._utils import interpolate_str as _interpolate
Expand DownExpand Up@@ -84,6 +88,7 @@ def __init__(
external_scripts=None,
external_stylesheets=None,
suppress_callback_exceptions=None,
suppress_validation_exceptions=None,
components_cache_max_age=None,
**kwargs):

Expand DownExpand Up@@ -126,6 +131,10 @@ def __init__(
'suppress_callback_exceptions',
suppress_callback_exceptions, env_configs, False
),
'suppress_validation_exceptions': _configs.get_config(
Comment thread
rmarren1 marked this conversation as resolved.
'suppress_validation_exceptions',
suppress_validation_exceptions, env_configs, False
),
'routes_pathname_prefix': routes_pathname_prefix,
'requests_pathname_prefix': requests_pathname_prefix,
'include_assets_files': _configs.get_config(
Expand DownExpand Up@@ -168,6 +177,7 @@ def _handle_error(error):
self.assets_ignore = assets_ignore

self.registered_paths = {}
self.namespaces = {}

# urls
self.routes = []
Expand DownExpand Up@@ -256,7 +266,6 @@ def layout(self, value):
'a dash component.')

self._layout = value

layout_value = self._layout_value()
# pylint: disable=protected-access
self.css._update_layout(layout_value)
Expand DownExpand Up@@ -575,7 +584,7 @@ def react(self, *args, **kwargs):
'Use `callback` instead. `callback` has a new syntax too, '
'so make sure to call `help(app.callback)` to learn more.')

def _validate_callback(self, output, inputs, state, events):
def _validate_callback_definition(self, output, inputs, state, events):
# pylint: disable=too-many-branches
layout = self._cached_layout or self._layout_value()

Expand DownExpand Up@@ -713,7 +722,7 @@ def _validate_callback(self, output, inputs, state, events):
output.component_id,
output.component_property).replace(' ', ''))

def _validate_callback_output(self, output_value, output):
def _debug_callback_serialization_error(self, output_value, output):
valid = [str, dict, int, float, type(None), Component]

def _raise_invalid(bad_val, outer_val, bad_type, path, index=None,
Expand DownExpand Up@@ -831,7 +840,7 @@ def _validate_value(val, index=None):
# relationships
# pylint: disable=dangerous-default-value
def callback(self, output, inputs=[], state=[], events=[]):
self._validate_callback(output, inputs, state, events)
self._validate_callback_definition(output, inputs, state, events)

callback_id = '{}.{}'.format(
output.component_id, output.component_property
Expand All@@ -853,13 +862,11 @@ def callback(self, output, inputs=[], state=[], events=[]):

def wrap_func(func):
@wraps(func)
def add_context(*args, **kwargs):

output_value = func(*args, **kwargs)
def add_context(validated_output):
response = {
'response': {
'props': {
output.component_property: output_value
output.component_property: validated_output
}
}
}
Expand All@@ -870,7 +877,10 @@ def add_context(*args, **kwargs):
cls=plotly.utils.PlotlyJSONEncoder
)
except TypeError:
self._validate_callback_output(output_value, output)
self._debug_callback_serialization_error(
validated_output,
output
)
raise exceptions.InvalidCallbackReturnValue('''
The callback for property `{property:s}`
of component `{id:s}` returned a value
Expand All@@ -887,6 +897,7 @@ def add_context(*args, **kwargs):
mimetype='application/json'
)

self.callback_map[callback_id]['func'] = func
self.callback_map[callback_id]['callback'] = add_context

return add_context
Expand DownExpand Up@@ -915,7 +926,88 @@ def dispatch(self):
c['id'] == component_registration['id']
][0])

return self.callback_map[target_id]['callback'](*args)
output_value = self.callback_map[target_id]['func'](*args)

# Only validate if we get required information from renderer
# and validation is not turned off by user
if (
(not self.config.suppress_validation_exceptions) and
Comment thread
rmarren1 marked this conversation as resolved.
'namespace' in output and
'type' in output
):
# Python2.7 might make these keys and values unicode
namespace = str(output['namespace'])
component_type = str(output['type'])
component_id = str(output['id'])
component_property = str(output['property'])
callback_func_name = self.callback_map[target_id]['func'].__name__
self._validate_callback_output(namespace, component_type,
component_id, component_property,
callback_func_name,
args, output_value)

return self.callback_map[target_id]['callback'](output_value)

def _validate_callback_output(self, namespace, component_type,
component_id, component_property,
callback_func_name, args, value):
module = sys.modules[namespace]
Comment thread
rmarren1 marked this conversation as resolved.
component = getattr(module, component_type)
# pylint: disable=protected-access
validator = DashValidator({
component_property: component._schema.get(component_property, {})
})
valid = validator.validate({component_property: value})
if not valid:
error_message = dedent("""\

A Dash Callback produced an invalid value!

Dash tried to update the `{component_property}` prop of the
`{component_name}` with id `{component_id}` by calling the
`{callback_func_name}` function with `{args}` as arguments.

This function call returned `{value}`, which did not pass
validation tests for the `{component_name}` component.

The expected schema for the `{component_property}` prop of the
`{component_name}` component is:

***************************************************************
{component_schema}
***************************************************************

The errors in validation are as follows:

""").format(
component_property=component_property,
component_name=component.__name__,
component_id=component_id,
callback_func_name=callback_func_name,
args='({})'.format(", ".join(map(repr, args))),
value=value,
component_schema=pprint.pformat(
component._schema[component_property]
)
)

error_message = generate_validation_error_message(
validator.errors,
0,
error_message
) + dedent("""
You can turn off these validation exceptions by setting
`app.config.suppress_validation_exceptions=True`
Comment thread
rmarren1 marked this conversation as resolved.
""")

raise exceptions.CallbackOutputValidationError(error_message)
# Must also validate initialization of newly created components
if component_property == 'children':
if isinstance(value, Component):
value.validate()
for component in value.traverse():
if isinstance(component, Component):
component.validate()

def _validate_layout(self):
if self.layout is None:
Expand All@@ -932,6 +1024,11 @@ def _validate_layout(self):

component_ids = {layout_id} if layout_id else set()
for component in to_validate.traverse():
if (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Normally there is no () after if in python.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how else to style since the if statement is > 80 characters. PEP isn't super specific about what to do here: https://www.python.org/dev/peps/pep-0008/#multiline-if-statements.

not self.config.suppress_validation_exceptions and
isinstance(component, Component)
):
component.validate()
component_id = getattr(component, 'id', None)
if component_id and component_id in component_ids:
raise exceptions.DuplicateIdError(
Expand DownExpand Up@@ -1057,5 +1154,9 @@ def run_server(self,
:return:
"""
debug = self.enable_dev_tools(debug, dev_tools_serve_dev_bundles)
if not debug:
# Do not throw debugging exceptions in production.
self.config.suppress_validation_exceptions = True
self.config.suppress_callback_exceptions = True
self.server.run(port=port, debug=debug,
**flask_run_options)
Loading