Python Dash基本身份验证-在应用中获取用户名

时间:2018-08-01 17:24:10

标签: python authentication web-applications callback plotly-dash

我目前正在制作一个Dash应用程序,该应用程序将根据用户权限显示不同的布局,因此我希望能够识别已注册的用户。我正在使用基本身份验证,并在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'对象没有属性'_username'错误。

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

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

1 个答案:

答案 0 :(得分: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)

我希望这会有所帮助!

相关问题