简体   繁体   中英

Python Dash: How to update same local storage using two callbacks?

Below is my callback for logging into my application when the login button is clicked.

@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'

I want to clear my local storage in the similar way when I logout. But I am unable to use Output('local', 'data') as it causes duplication issue. How to clear the local storage without getting into duplication issue?

In Dash, you can only target each Output once . If you want to add a clear button, you would need to add the button as an Input of the current callback and implement appropriate delegation logic.

The GroupTransform from dash-extensions provides syntactical sugar via a group keyword argument. Callbacks within the same group are bundled into one, enabling you to write code like

@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"

For completeness, here is a full example tested with 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM