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

标签 python flask plotly-dash flask-login

我正在尝试构建一个集成在 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')

@application.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    if form.validate_on_submit():
        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('/app1/')

@application.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('login'))

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

请建议如何解决我的问题。谢谢!

最佳答案

在一些帮助下我设法解决了这个问题。以防万一有人被卡住,请参阅下面更新的代码。

添加了 session 行以在 routes.py 中存储当前用户名:

from flask import render_template, flash, redirect, url_for, request, session
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')

@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'))

以及app1.py回调中的session:

import dash
import dash_html_components as html
from dash.dependencies import Input, Output
from dashapp import application
from flask_login import login_required
from flask import session

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 = [
        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])

关于python - 将 current_user 从 Flask-Login 传递到 Plotly Dash 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58379772/

相关文章:

python - Pandas:如果字符串列表中不存在,则将其替换为 'other'

集合中元素的python顺序

python - python和 Elasticsearch 更新错误

javascript - Flask 从 PushState 接收 url 更改

python - Dask 加载 JSON(用于实时绘图)

python -/admin/ 'set' 对象的类型错误是不可逆的,并且要反转的参数 ( ) 必须是一个序列

python - 如何表示 scipy.optimization 中变量的界限,其中界限是另一个变量的函数

python-3.x - 在浏览器网络应用程序中同时对两个视频进行姿势检测不起作用

python - 如何通过 flask.Blueprint.route 装饰器传递类的 self ?

python - 语法错误: “],” invalid syntax - Dash Graph Building