【问题标题】:Python Dash Basic Auth - get username in appPython Dash Basic Auth - 在应用程序中获取用户名
【发布时间】:2019-01-09 08:43:30
【问题描述】:

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

不幸的是,当我尝试使用身份验证中的 _username 属性时,我收到了:AttributeError: 'BasicAuth' object has no attribute '_username' 错误。

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

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

【问题讨论】:

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


    【解决方案1】:

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

    我希望这会有所帮助!

    【讨论】:

    • 集成到现有仪表板应用程序中非常简单。值得注意的是,您可能需要安装dash_auth
    • 基于此示例,很明显您必须将 flask.request 放入回调函数中,否则您会收到“应用程序上下文之外”错误。这个例子真的很有效,谢谢
    猜你喜欢
    • 2020-07-13
    • 2022-08-03
    • 2014-07-18
    • 1970-01-01
    • 2020-10-21
    • 2020-11-11
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多