2 回答
TA贡献1789条经验 获得超8个赞
我设法在一些帮助下解决了这个问题。以防万一有人卡住,请参阅下面的更新代码。
添加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'))
在session回调中app1.py:
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])
TA贡献1777条经验 获得超10个赞
面临同样的问题。我想问题是当“应用程序”注册 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 ''
添加回答
举报