Skip to content

Commit f6b23f5

Browse files
authored
Fix use of orjson (#428)
* Ensure promises are not passed to orjson * Move patch version number Co-authored-by: delsim <dev@gibbsconsulting.ca> Addrresses #421 #404
1 parent 178ae6f commit f6b23f5

File tree

2 files changed

+28
-5
lines changed

2 files changed

+28
-5
lines changed

django_plotly_dash/_patches.py

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,22 +29,42 @@
2929
import json
3030

3131

32-
from plotly.io._json import config
32+
from plotly.io._json import config, clean_to_json_compatible
3333
from plotly.utils import PlotlyJSONEncoder
3434

3535
from _plotly_utils.optional_imports import get_module
36-
from django.utils.encoding import force_text
36+
from django.utils.encoding import force_str
3737
from django.utils.functional import Promise
3838

3939

4040
class DjangoPlotlyJSONEncoder(PlotlyJSONEncoder):
4141
"""Augment the PlotlyJSONEncoder class with Django delayed processing"""
4242
def default(self, obj):
4343
if isinstance(obj, Promise):
44-
return force_text(obj)
44+
return force_str(obj)
4545
return super().default(obj)
4646

4747

48+
def promise_clean_to_json_compatible(obj):
49+
50+
if isinstance(obj, dict):
51+
return {promise_clean_to_json_compatible(k): promise_clean_to_json_compatible(v) for k, v in obj.items()}
52+
53+
if isinstance(obj, (list, tuple)):
54+
if obj:
55+
return [promise_clean_to_json_compatible(v) for v in obj]
56+
57+
if isinstance(obj, Promise):
58+
return force_str(obj)
59+
60+
#try:
61+
# return obj.to_plotly_json()
62+
#except AttributeError:
63+
# pass
64+
65+
return obj
66+
67+
4868
def to_json_django_plotly(plotly_object, pretty=False, engine=None):
4969
"""
5070
Convert a plotly/Dash object to a JSON string representation
@@ -115,6 +135,7 @@ def to_json_django_plotly(plotly_object, pretty=False, engine=None):
115135
opts |= orjson.OPT_INDENT_2
116136

117137
# Plotly
138+
118139
try:
119140
plotly_object = plotly_object.to_plotly_json()
120141
except AttributeError:
@@ -132,8 +153,10 @@ def to_json_django_plotly(plotly_object, pretty=False, engine=None):
132153
datetime_allowed=True,
133154
modules=modules,
134155
)
135-
return orjson.dumps(cleaned, option=opts).decode("utf8")
136156

157+
cleaned = promise_clean_to_json_compatible(cleaned)
158+
159+
return orjson.dumps(cleaned, option=opts).decode("utf8")
137160

138161
import plotly.io.json
139162
plotly.io.json.to_json_plotly = to_json_django_plotly

django_plotly_dash/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,4 @@
2323
2424
'''
2525

26-
__version__ = "2.1.1"
26+
__version__ = "2.1.2"

0 commit comments

Comments
 (0)