Python Dash Basic Auth - 在应用程序中获取用户名

Python Dash Basic Auth - get username in app

我目前正在制作一个 Dash 应用程序,它会根据用户权限显示不同的布局,因此我希望能够识别已注册的用户。我正在使用 Basic Auth 并更改了 dash_auth/basic_auth.py 中的一些行: 原文:

username_password_utf8 = username_password.decode('utf-8')
username, password = username_password_utf8.split(':')

至:

username_password_utf8 = username_password.decode('utf-8')
username, password = username_password_utf8.split(':')
self._username = username

不幸的是,当我尝试使用来自 auth 的 _username 属性时,我收到了:AttributeError: 'BasicAuth' object has no attribute '_username' 错误。

app.layout = html.Div(
    html.H3("Hello " + auth._username)
)

我知道 Dash 应用程序在授权检查之前已经处理过了,但我不知道在哪里实现根据用户名更改布局的回调。如何在 Dash 应用程序中获取用户名?

基本上,您可以使用flask.request访问授权信息。

这是一个基于 dash authentication documentation.

的最小工作示例
import dash
import dash_auth
import dash_html_components as html
from dash.dependencies import Input, Output
from flask import request

# Keep this out of source code repository - save in a file or a database
VALID_USERNAME_PASSWORD_PAIRS = [
    ['hello', 'world']
]

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
auth = dash_auth.BasicAuth(
    app,
    VALID_USERNAME_PASSWORD_PAIRS
)

app.layout = html.Div([

    html.H2(id='show-output', children=''),
    html.Button('press to show username', id='button')

], className='container')

@app.callback(
    Output(component_id='show-output', component_property='children'),
    [Input(component_id='button', component_property='n_clicks')]
)
def update_output_div(n_clicks):
    username = request.authorization['username']
    if n_clicks:
        return username
    else:
        return ''

app.scripts.config.serve_locally = True


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

希望对您有所帮助!