[英]Sharing data between URLs in plotly-dash
我想在 URL 之間共享數據,但隱藏的 div 沒有作為回調 function 中的參數更新,盡管它在頁面中已明確更新。
復制的最小示例:
代碼:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
app = dash.Dash(__name__, external_stylesheets=[])
layout = [dcc.Location(id='url', refresh=False)]
layout += [html.Div(id='page-content')]
layout += [html.Div(children="default",
id='cache', style={"display": "none"})]
app.layout = html.Div(layout)
@app.callback(
[Output('page-content', 'children'),
Output('cache', "children")],
[Input('url', 'pathname')],
[State('cache', 'children')],
)
def route(pathname, data):
print(data)
if "/2/" in pathname:
return html.A(html.H2("1"), href="/1/"), dash.no_update
elif pathname == "/1/":
return html.A(html.H2("2"), href="/2/"), "1"
else:
return html.A(html.H2("2"), href="/2/"), "1"
if __name__ == '__main__':
app.run_server(debug=True)
控制台 output(切換頁面幾次后):
Dash is running on http://127.0.0.1:8050/
* Serving Flask app "app2" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
default
default
default
default
default
default
default
default
default
default
default
default
default
default
鉻截圖:
在我的實際應用程序頁面“2”中從數據庫查詢數據,我想在頁面“1”中使用該數據來最小化查詢。
我認為不知何故存在時間問題,但我不明白為什么默認值在被覆蓋后再次設置。
很感謝任何形式的幫助。
提前致謝!
使用商店的解決方法:只需將隱藏的 div 替換為 dcc.Store 與 storage_type session 或本地
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
app = dash.Dash(__name__, external_stylesheets=[])
layout = [dcc.Location(id='url', refresh=False)]
layout += [html.Div(id='page-content')]
layout += [dcc.Store(id='cache', storage_type='session')]
app.layout = html.Div(layout)
@app.callback(
[Output('page-content', 'children'),
Output('cache', "data")],
[Input('url', 'pathname')],
[State('cache', 'data')],
)
def route(pathname, data):
print(data)
if "/2/" in pathname:
return html.A(html.H2("1"), href="/1/"), dash.no_update
elif pathname == "/1/":
return html.A(html.H2("2"), href="/2/"), "1"
else:
return html.A(html.H2("2"), href="/2/"), "1"
if __name__ == '__main__':
app.run_server(debug=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.