以下是单击登录按钮时登录应用程序的回调。
@app.callback([Output('local', 'data'), Output('redirect-url', 'pathname')],
[Input('loginButton', 'n_clicks')],
[State('usernameBox', 'value'),
State('passwordBox', 'value'),
State('local', 'data'),
])
def login(n_clicks, username, password, local_storage):
if local_storage is None or not isinstance(local_storage, dict):
local_storage = {}
if n_clicks:
try:
if len(username) > 0 and len(password) > 0:
local_storage['user_token'] = 'bearer '+generate_token(username, password)
app_layout.update_layout(app)
# update the local storage and redirects to home page
return local_storage, ''
except Exception as e:
print(traceback.format_exc())
pass
# refresh the login page
return local_storage, '/login'
我想在注销时以类似的方式清除本地存储。但我无法使用Output("local","data"(,因为它会导致重复问题。如何在不出现重复问题的情况下清除本地存储?
在Dash中,您只能针对每个Output
一次。如果要添加清除按钮,则需要将该按钮添加为当前回调的Input
,并实现适当的委派逻辑。
来自dash-extensions
的GroupTransform
通过group
关键字参数提供语法糖。同一组内的回调被绑定到一个组中,使您能够编写类似的代码
@app.callback(Output("log", "children"), Input("left", "n_clicks"), group="my_group")
def left(n_clicks):
return "left"
@app.callback(Output("log", "children"), Input("right", "n_clicks"), group="my_group")
def right(n_clicks):
return "right"
为了完整起见,这里是一个用dash-extensions==0.0.41
测试的完整示例
import dash_html_components as html
from dash_extensions.enrich import Output, DashProxy, Trigger, TriggerTransform, GroupTransform
app = DashProxy(prevent_initial_callbacks=True, transforms=[TriggerTransform(), GroupTransform()])
app.layout = html.Div([
html.Button("Left", id="left"), html.Button("Right", id="right"), html.Div(id="log"),
])
@app.callback(Output("log", "children"), Trigger("left", "n_clicks"), group="lr") # targets same output as right
def left():
return "left"
@app.callback(Output("log", "children"), Trigger("right", "n_clicks"), group="lr") # targets same output as left
def right():
return "right"
if __name__ == '__main__':
app.run_server()