okomarov / dash_on_flask

Dash on Flask with login_required (and application factory pattern)
MIT License
286 stars 126 forks source link

Passing User Data into Dash App #14

Closed DanielHHowell closed 3 years ago

DanielHHowell commented 3 years ago

Thanks so much for this great work!

I've got everything running perfectly, but one hurdle I am trying to overcome is how to pass the current user into the dash app. I realize it's instantiated through login_required(), and would generally use current_user.username or store it in a session['username'] but can't figure out how to do it in this case. Any pointers for this?

Much thanks in advance!

okomarov commented 3 years ago

Can you give a code snippet?

The views are protected with a login_required already and the dashapps are instantiated with flask's context, so you should just be able to import the current_user.

DanielHHowell commented 3 years ago

Thanks for the quick reply. So something like this:

from flask import session
from flask_login import login_required, current_user
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
# Import factory method
from app import create_app

def protect_dashviews(dashapp):
    for view_func in dashapp.server.view_functions:
        if view_func.startswith(dashapp.config['url_base_pathname']):
            dashapp.server.view_functions[view_func] = login_required(dashapp.server.view_functions[view_func])

# Create Flask server app
server = create_app()

# Create dash app passing our server
dashapp = dash.Dash(__name__, server=server, url_base_pathname='/dashboard/')
protect_dashviews(dashapp)

with server.app_context():

    dashapp.layout = html.P(str(current_user.username))

The current_user object passed is None so all the attributes are also inaccessible.

okomarov commented 3 years ago

First thing that jumps to the eye is that this solution is missing the login_required user loader.

Have you tried using the code from this repo as a template and pick the things that you need by deleting from it rather than composing? I am afraid I won't be able to support composable patterns as there are simply too many moving parts (which was the motivation for this template in the first place).

DanielHHowell commented 3 years ago

I think the problem was that there was a new server instance, so the previous current_user couldn't be sent. For others searching, I found the dash-auth-flow repo more suited for this particular purpose.

sorenwacker commented 3 years ago

I have the same question.

okomarov commented 3 years ago

@sorenwacker I've addressed this in the latest commit https://github.com/okomarov/dash_on_flask/commit/9066685b14a683085ce78a8b327ce33d20493082 which was a response to https://github.com/okomarov/dash_on_flask/issues/21