Use Flask session


#1

Hi all,

I’m new to python and Dash. Dash “Written on top of Flask”. I need to use the flask session.

I’ll try by declaring Dash
app = dash.Dash(name, external_stylesheets=external_stylesheets)

I need to set the secretge key but my object app dooesn’t have the secret_key attribute like a Flask object.

How to use session/cookies with Dash?

Thanks in advance,
Vladimiro Puggelli


#2

You can access the underlying flask server with app.server. So to access the secret_key attribute do app.server.secret_key. You can also create and configure your own flask server and pass it into the Dash app like this if you like

server = flask.Flask(__name__, ...)
app = dash.Dash(server=server, ...)

#3

Great! Thank you very much!


#4

Now another problem. I may access my session in my Dash object, trough a callback for example. How to access session in a html object. In this example I need to set the initial value of my dropdown to the value saved in session. How can I do it? Some “onPageLoad” method? How to access session out of my Dash object?

Thanks in advance,
Vladimiro

layout = html.Div([
dcc.Dropdown(
id=‘app-1-dropdown’,
options=[
{‘label’: ‘App 1 - {}’.format(i), ‘value’: i} for i in [
‘NYC’, ‘MTL’, ‘LA’
]
],
value=session[‘app-1-display-val-session’]
#]
),
html.Div(id=‘app-1-display-value’),
dcc.Link(‘Go to App 2’, href=’/apps/app2’)
])

@app.callback(
Output(‘app-1-display-value’, ‘children’),
[Input(‘app-1-dropdown’, ‘value’)])
def display_value(value):
session[‘app-1-display-val-session’] = value
if ‘app-1-display-val-session’ not in session:
return ‘Prova sessione non riuscita’
return ‘You have selected “{}”’.format(session[‘app-1-display-val-session’])


#5

The Flask session global must be accessed within a request context. That means that you can’t define it within a static layout that is evaluation when the app first loads. You need to use it within a dynamic layout, where app.layout is assigned a function object, meaning that the function will be evaluated on each page load. See the Updates on Page Load section in the Dash Guide.


#6

Thanks ned, meanwhile i have resolve my problem with Flask documentation. :wink:

For other user reference:
@app.server.route(’/’)
def create_layout():
layout02 = html.Div([
html.H3(‘App 1’),
dcc.Dropdown(
id=‘app-1-dropdown’,
options=[
{‘label’: ‘App 1 - {}’.format(i), ‘value’: i} for i in [
‘NYC’, ‘MTL’, ‘LA’
]
],
value=session[‘app-1-display-val-session’]
),
html.Div(id=‘app-1-display-value’),
dcc.Link(‘Go to App 2’, href=’/apps/app2’)
])
return layout02

Thanks to community. I have started this week my Python/Dash/Flask adventure. :slight_smile:


#7

Awesome, great to hear!