Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

plotly - How to reload layout in Python Dash every time page is reloaded when app is passed as parameter?

If you want to reload layout every page reload you do this:

app.layout = myfunction

NOTE: calling my function without parenthesis, like this would be wrong:

app.layout = myfunction()

But what if I want to call that function passing parameters?

app.layout = myfunction????

I’ve made a workaround by creating a dummy function like this

def serve_layout():
    return layout(app) # I pass app to use app.callbacks

app.layout = serve_layout

However

I am getting lots of errors about callbacks telling me that there are duplicate callbacks, which there really aren’t.

ERROR:

In the callback for output(s):
  information-container.style
Output 0 (information-container.style) is already in use.
Any given output can only have one callback that sets it.
To resolve this situation, try combining these into
one callback function, distinguishing the trigger
by using `dash.callback_context` if necessary.

I think this error is because I am passing the app as parameter (I need to do this to manage app.callbacks for every component because my app is pretty large) and somehow this type of paradigm is conflicting with Dash paradigm.

Any help is appreciated

source code:


import dash
from layout import layout # layout is where i define all layout logic/ components

def serve_layout():
    return layout(app)

app = dash.Dash(__name__)

app.layout = serve_layout
app.title = 'Example app'
if __name__ == "__main__":
    app.run_server(debug=True,
                   host='0.0.0.0')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With your current code, you are registering the callbacks every time the page is loaded, which is why you get an error. You should split your current serve_layout function into two functions,

  • A layout function (with no arguments) that only renders the layout
  • Another function, say callbacks, that takes the app as an argument and registers the callbacks

and the app should then be setup using code like,

...
app.layout = layout 
callbacks(app)
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...