flask - 在 gunicorn 中运行的 Plotly Dash 中获取请求头

标签 flask plotly-dash

这与此有关post但解决方案不起作用。

我有 SSO 身份验证,传递带有用户名的请求 header 。在 Flask 应用程序中,我可以使用 flask.request.headers['username'] 取回用户名。在 Dash 中,我收到服务器错误。这是 Dash 应用程序 - 它正在使用 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()


如有任何帮助,我们将不胜感激。

最佳答案

您只能从请求上下文中访问 request 对象。在 Dash 术语中,这意味着来自回调。这是一个小例子,

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()

关于flask - 在 gunicorn 中运行的 Plotly Dash 中获取请求头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70935643/

相关文章:

python - 使用flask-zodb的LockError

cytoscape.js - 用户移动节点后,如何在 Dash/Cytoscape 中找到节点的位置?

python - 如何在按钮上添加单独的 Html 元素单击 Python Dash

python - 阴谋冲刺 : Render a Graph only if certain data in a Pandas DataFrame exists

Python scrapy ReactorNotRestartable 替代品

python - (psycopg2.OperationalError) SSL SYSCALL 错误 : Software caused connection abort

linux - 启动后自动运行 flask 应用程序无法正常工作

javascript - 在更新时显示日志文件的内容

python - Plotly 中的一个图有两个或三个颜色条

python-3.x - Plotly Dash 应用程序中的重定向