-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Give a more informative error for JSON not serializable. (#269) #273
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
433a65e
More informative JSON not serializable errors with paths.
rmarren1 6bba6e9
Edge cases for JSON exception, and better formatting.
rmarren1 ba33c6e
Minor formatting updates.
rmarren1 ab441f4
Tab out singular elements in json exceptions to match list elements.
rmarren1 7f609e8
Change prefix for singleton components from '- ' to '[*] '
rmarren1 ee8a489
Only validate callback to throw exception after failure to serialize.
rmarren1 ed4ecf0
Throw default exception if `_validate_callback_output` doesn't catch
rmarren1 718e259
Change `ReturnValueNotJSONSerializable` to `InvalidCallbackReturnValue`
rmarren1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -475,6 +475,110 @@ def _validate_callback(self, output, inputs, state, events): | |
output.component_id, | ||
output.component_property).replace(' ', '')) | ||
|
||
def _validate_callback_output(self, output_value, output): | ||
valid = [str, dict, int, float, type(None), Component] | ||
|
||
def _raise_invalid(bad_val, outer_val, bad_type, path, index=None, | ||
toplevel=False): | ||
outer_id = "(id={:s})".format(outer_val.id) \ | ||
if getattr(outer_val, 'id', False) else '' | ||
outer_type = type(outer_val).__name__ | ||
raise exceptions.InvalidCallbackReturnValue(''' | ||
The callback for property `{property:s}` of component `{id:s}` | ||
returned a {object:s} having type `{type:s}` | ||
which is not JSON serializable. | ||
|
||
{location_header:s}{location:s} | ||
and has string representation | ||
`{bad_val}` | ||
|
||
In general, Dash properties can only be | ||
dash components, strings, dictionaries, numbers, None, | ||
or lists of those. | ||
'''.format( | ||
property=output.component_property, | ||
id=output.component_id, | ||
object='tree with one value' if not toplevel else 'value', | ||
type=bad_type, | ||
location_header=( | ||
'The value in question is located at' | ||
if not toplevel else | ||
'''The value in question is either the only value returned, | ||
or is in the top level of the returned list,''' | ||
), | ||
location=( | ||
"\n" + | ||
("[{:d}] {:s} {:s}".format(index, outer_type, outer_id) | ||
if index is not None | ||
else ('[*] ' + outer_type + ' ' + outer_id)) | ||
+ "\n" + path + "\n" | ||
) if not toplevel else '', | ||
bad_val=bad_val).replace(' ', '')) | ||
|
||
def _value_is_valid(val): | ||
return ( | ||
# pylint: disable=unused-variable | ||
any([isinstance(val, x) for x in valid]) or | ||
type(val).__name__ == 'unicode' | ||
) | ||
|
||
def _validate_value(val, index=None): | ||
# val is a Component | ||
if isinstance(val, Component): | ||
for p, j in val.traverse_with_paths(): | ||
# check each component value in the tree | ||
if not _value_is_valid(j): | ||
_raise_invalid( | ||
bad_val=j, | ||
outer_val=val, | ||
bad_type=type(j).__name__, | ||
path=p, | ||
index=index | ||
) | ||
|
||
# Children that are not of type Component or | ||
# collections.MutableSequence not returned by traverse | ||
child = getattr(j, 'children', None) | ||
if not isinstance(child, collections.MutableSequence): | ||
if child and not _value_is_valid(child): | ||
_raise_invalid( | ||
bad_val=child, | ||
outer_val=val, | ||
bad_type=type(child).__name__, | ||
path=p + "\n" + "[*] " + type(child).__name__, | ||
index=index | ||
) | ||
|
||
# Also check the child of val, as it will not be returned | ||
child = getattr(val, 'children', None) | ||
if not isinstance(child, collections.MutableSequence): | ||
if child and not _value_is_valid(child): | ||
_raise_invalid( | ||
bad_val=child, | ||
outer_val=val, | ||
bad_type=type(child).__name__, | ||
path=type(child).__name__, | ||
index=index | ||
) | ||
|
||
# val is not a Component, but is at the top level of tree | ||
else: | ||
if not _value_is_valid(val): | ||
_raise_invalid( | ||
bad_val=val, | ||
outer_val=type(val).__name__, | ||
bad_type=type(val).__name__, | ||
path='', | ||
index=index, | ||
toplevel=True | ||
) | ||
|
||
if isinstance(output_value, list): | ||
for i, val in enumerate(output_value): | ||
_validate_value(val, index=i) | ||
else: | ||
_validate_value(output_value) | ||
|
||
# TODO - Update nomenclature. | ||
# "Parents" and "Children" should refer to the DOM tree | ||
# and not the dependency tree. | ||
|
@@ -521,9 +625,26 @@ def add_context(*args, **kwargs): | |
} | ||
} | ||
|
||
try: | ||
jsonResponse = json.dumps( | ||
response, | ||
cls=plotly.utils.PlotlyJSONEncoder | ||
) | ||
except TypeError: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 perfect |
||
self._validate_callback_output(output_value, output) | ||
raise exceptions.InvalidCallbackReturnValue(''' | ||
The callback for property `{property:s}` | ||
of component `{id:s}` returned a value | ||
which is not JSON serializable. | ||
|
||
In general, Dash properties can only be | ||
dash components, strings, dictionaries, numbers, None, | ||
or lists of those. | ||
'''.format(property=output.component_property, | ||
id=output.component_id)) | ||
|
||
return flask.Response( | ||
json.dumps(response, | ||
cls=plotly.utils.PlotlyJSONEncoder), | ||
jsonResponse, | ||
mimetype='application/json' | ||
) | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -12,4 +12,4 @@ six | |
plotly>=2.0.8 | ||
requests[security] | ||
flake8 | ||
pylint | ||
pylint==1.9.2 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since we JSON serialize with the
json.dumps(obj, cls=plotly.utils.PlotlyJSONEncoder)
, this list actually has a few other items: https://github.com/plotly/plotly.py/blob/6b3a0135977b92b3f7e0be2a1e8b418d995c70e3/plotly/utils.py#L137-L332So, if there was a component property that accepted a list of numbers, then technically the user could return a numpy array or a dataframe.
The only example that immediately comes to mind is updating the
figure
property in a callback with theplotly.graph_objs
. These objects get serialized because they have ato_plotly_json
method.So, I wonder if instead of validating up-front, we should only run this routine only if our
json.dumps(resp, plotly.utils.PlotlyJSONEncoder)
call fails.This would have the other advantage of being faster for the non-error case. If the user returns a huge object (e.g. some of my callbacks in apps return a 2MB nested component), doing this recursive validation might be slow.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That makes sense. I am not sure how large of a speed up that would be since validating a large callback output is likely much faster than the network delay of sending that large output, but it definitely makes it easier than crafting a perfect validator (that would need to update every time we want to extend
PlotlyJSONEncoder
).