2
votes

I have a simple Dash callback function like following:

@app.callback(
    dash.dependencies.Output('test_output', 'children'),
    [dash.dependencies.Input('test_input', 'value')]):
def process(val):
    return html.Div('test')

And now I'm going to set some cookies. As we can see in the source code of Dash, wrapper function makes usual Flask Response object with serialized returned data:

def wrap_func(func):
    def add_context(*args, **kwargs):

        output_value = func(*args, **kwargs)
        response = {
            'response': {
                'props': {
                    output.component_property: output_value
                }
            }
        }

        return flask.Response(
            json.dumps(response,
                       cls=plotly.utils.PlotlyJSONEncoder),
            mimetype='application/json'
        )

    self.callback_map[callback_id]['callback'] = add_context

    return add_context

So if this code were a part of my project, I would use Response.set_cookie here.

The situation with sessions seems to be different - I can access and modify session objects from the wrapped function that results in modifying session cookie.

How can I set and get cookies from Dash callback? Maybe Flask has a way to do such thing without directly creating Response object?

UPDATE

I've created an issue for this: https://github.com/plotly/dash/issues/182

And pull request to add this functionality: https://github.com/plotly/dash/pull/183

1

1 Answers

4
votes

The functionality you are looking for was ultimately merged in: https://github.com/plotly/dash/pull/623 (on March 4th 2019)

Their example on how to set a cookie looks like this:

@app.callback(Output('output', 'children'), [Input('input', 'value')])
def update_output(value):
    dash.callback_context.response.set_cookie(
        'dash cookie', value + ' - cookie')
    return value + ' - output'