将 current_user 从 Flask-Login 传递到 Plotly Dash 应用程序

我正在尝试构建一个集成在 Flask 应用程序中的 Dash 应用程序。一切似乎都运行良好,但是当我尝试在 Dash 应用程序中显示登录用户时,它显示为“无”。


我的应用程序结构如下:


example/

example/

  dashapp/

    static/

      custom-css.css

    templates/

      base.html

      home.html

      login.html

    __init__.py

    app1.py

    forms.py

    models.py

    routes.py

  application.py

  config.py

  users.db

我的 Dash 应用程序位于app1.py. 我尝试了几种方法通过current_user但没有成功。虽然它出来很好home.html。我想问题在于我的应用程序位于单独的文件中,而不是routes.py.


这是代码app.py:


import dash

import dash_html_components as html

from dashapp import application

from flask_login import login_required, current_user



app1 = dash.Dash(__name__, server = application, routes_pathname_prefix = '/app1/', assets_folder = 'static', assets_url_path = '/static')

app1.scripts.config.serve_locally = True

app1.css.config.serve_locally = True


app1.layout = html.Div(

    children = '{}'.format(current_user)

)


for view_func in app1.server.view_functions:

    if view_func.startswith('/app1/'):

        app1.server.view_functions[view_func] = login_required(app1.server.view_functions[view_func])

routes.py代码:


from flask import render_template, flash, redirect, url_for, request

from flask_login import login_user, logout_user, current_user, login_required

from werkzeug.urls import url_parse

from dashapp import application, db

from dashapp.forms import LoginForm

from dashapp.models import User

from dashapp import app1



@application.route('/')

@application.route('/home')

@login_required

def home():

    return render_template('home.html')

其他脚本几乎是标准的,除非真的需要它们,否则我不会将它们包含在问题中。


请建议如何克服我的问题。谢谢!


慕桂英546537
浏览 125回答 2
2回答

拉丁的传说

我设法在一些帮助下解决了这个问题。以防万一有人卡住,请参阅下面的更新代码。添加session了行以将当前用户名存储在routes.py:from flask import render_template, flash, redirect, url_for, request, sessionfrom flask_login import login_user, logout_user, current_user, login_requiredfrom werkzeug.urls import url_parsefrom dashapp import application, dbfrom dashapp.forms import LoginFormfrom dashapp.models import Userfrom dashapp import app1@application.route('/')@application.route('/home')@login_requireddef home():    return render_template('home.html')@application.route('/login', methods=['GET', 'POST'])def login():    if current_user.is_authenticated:        session['username'] = current_user.username        return redirect(url_for('home'))    form = LoginForm()    if form.validate_on_submit():        session['username'] = form.username.data        user = User.query.filter_by(username=form.username.data).first()        if user is None or not user.check_password(form.password.data):            flash('Invalid username or password')            return redirect(url_for('login'))        login_user(user, remember=form.remember_me.data)        next_page = request.args.get('next')        if not next_page or url_parse(next_page).netloc != '':            next_page = url_for('home')        return redirect(next_page)    return render_template('login.html', form=form)@application.route('/logout')def logout():    session.pop('username', None)    logout_user()    return redirect(url_for('login'))在session回调中app1.py:import dashimport dash_html_components as htmlfrom dash.dependencies import Input, Outputfrom dashapp import applicationfrom flask_login import login_requiredfrom flask import sessionapp1 = dash.Dash(__name__, server = application, routes_pathname_prefix = '/app1/', assets_folder = 'static', assets_url_path = '/static')app1.scripts.config.serve_locally = Trueapp1.css.config.serve_locally = Trueapp1.layout = html.Div(    children = [        html.Div(id='div2'),        html.Div(id='div3', children = 'xxxx'),    ],)@app1.callback(    Output('div2', 'children'),    [Input('div3', 'children')])def update_intervalCurrentTime(children):    return session.get('username', None)for view_func in app1.server.view_functions:    if view_func.startswith('/app1/'):        app1.server.view_functions[view_func] = login_required(app1.server.view_functions[view_func])

不负相思意

面临同样的问题。我想问题是当“应用程序”注册 Dash 应用程序时当前用户尚未初始化。很好的解决方法,虽然看起来有点不安全,因为 Flask 会话只是被编码的。https://github.com/RafaelMiquelino/dash-flask-login/blob/master/app.py - 我认为更强大的解决方案。它在回调中检查 current_user 并将页面的内容用作输入,因此在页面加载时调用回调。如果用户体验不是问题,您也可以跳过对视图的保护。这是我如何使用它的简化示例:@app.callback(    Output('graph-wrapper', 'children'),    [Input('page-content', 'children')])def load_graph(input1):    if current_user.is_authenticated:        return dcc.Graph() # Dash Graph populated with current_user data from db    else:        return ''
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java