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

问题描述 投票:1回答:1

我目前正在制作一个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

不幸的是,我收到了:AttributeError:当我尝试使用auth的_username属性时,'BasicAuth'对象没有属性'_username'错误。

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

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

python authentication web-applications callback plotly-dash
1个回答
2
投票

基本上,您可以使用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)

我希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.