Home > front end >  Get the request header in Plotly Dash running in gunicorn
Get the request header in Plotly Dash running in gunicorn

Time:02-02

This is related to this post but the solution does not work.

I have SSO auth passing in a request header with a username. In a Flask app I can get the username back using flask.request.headers['username']. In Dash I get a server error. Here is the Dash app - it is using gunicorn.

import dash
from dash import html
import plotly.graph_objects as go
from dash import dcc

from dash.dependencies import Input, Output
import flask
from flask import request

server = flask.Flask(__name__) # define flask app.server

app = dash.Dash(__name__, serve_locally=False, server=server)

username = request.headers['username']
greeting = "Hello "   username

app.layout = html.Div(children=[
    html.H1(children=greeting),

    html.Div(children='''
            Dash: A web application framework for Python.
        '''),

    dcc.Graph(
            id='example-graph',
            figure={
                'data': [
                    {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
                    {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
                ],
                'layout': {
                    'title': 'Dash Data Visualization'
                }
            }
        )
])

if __name__ == '__main__':
    app.run_server()


Any help would be much appreciated.

CodePudding user response:

You can only access the request object from within a request context. In Dash terminology that means from within a callback. Here is a small example,

from dash import html, Input, Output, Dash
from flask import request

app = Dash(__name__)
app.layout = html.Div(children=[
    html.Div(id="greeting"),
    html.Div(id="dummy")  # dummy element to trigger callback on page load
])


@app.callback(Output("greeting", "children"), Input("dummy", "children"))
def say_hello(_):
    host = request.headers['host']  # host should always be there
    return f"Hello from {host}!"


if __name__ == '__main__':
    app.run_server()
  •  Tags:  
  • Related