22from flask import Flask
33
44from django .urls import reverse
5+ from django .http import HttpResponse
6+
7+ import json
8+
9+ from plotly .utils import PlotlyJSONEncoder
510
611from .app_name import app_name
712
@@ -107,7 +112,7 @@ def run(self,*args,**kwargs):
107112 pass
108113
109114class NotDash (Dash ):
110- def __init__ (self , name_root , app_pathname , ** kwargs ):
115+ def __init__ (self , name_root , app_pathname = None , replacements = None , ** kwargs ):
111116
112117 global app_instances
113118 current_instances = app_instances .get (name_root ,None )
@@ -132,11 +137,52 @@ def __init__(self, name_root, app_pathname, **kwargs):
132137
133138 self ._adjust_id = False
134139 self ._dash_dispatch = not kwargs .get ('expanded_callbacks' ,False )
140+ if replacements :
141+ self ._replacements = replacements
142+ else :
143+ self ._replacements = dict ()
144+ self ._use_dash_layout = len (self ._replacements ) < 1
135145
136146 def use_dash_dispatch (self ):
137- # TODO make this be a function of using kwargs in callbacks
138147 return self ._dash_dispatch
139148
149+ def use_dash_layout (self ):
150+ return self ._use_dash_layout
151+
152+ def augment_initial_layout (self , base_response ):
153+ if self .use_dash_layout () and False :
154+ return HttpResponse (base_response .data ,
155+ content_type = base_response .mimetype )
156+ # Adjust the base layout response
157+ baseDataInBytes = base_response .data
158+ baseData = json .loads (baseDataInBytes .decode ('utf-8' ))
159+ # Walk tree. If at any point we have an element whose id matches, then replace any named values at this level
160+ reworked_data = self .walk_tree_and_replace (baseData )
161+ response_data = json .dumps (reworked_data ,
162+ cls = PlotlyJSONEncoder )
163+ return HttpResponse (response_data ,
164+ content_type = base_response .mimetype )
165+
166+ def walk_tree_and_replace (self , data ):
167+ if isinstance (data ,dict ):
168+ response = {}
169+ replacements = {}
170+ # look for id entry
171+ thisID = data .get ('id' ,None )
172+ if thisID is not None :
173+ replacements = self ._replacements .get (thisID ,{})
174+ # walk all keys and replace if needed
175+ for k , v in data .items ():
176+ r = replacements .get (k ,None )
177+ if r is None :
178+ r = self .walk_tree_and_replace (v )
179+ response [k ] = r
180+ return response
181+ if isinstance (data ,list ):
182+ # process each entry in turn and return
183+ return [self .walk_tree_and_replace (x ) for x in data ]
184+ return data
185+
140186 def flask_app (self ):
141187 return self ._flask_app
142188
0 commit comments