2 回答

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超8個(gè)贊
我設(shè)法在一些幫助下解決了這個(gè)問題。以防萬一有人卡住,請參閱下面的更新代碼。
添加session了行以將當(dāng)前用戶名存儲在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回調(diào)中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貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超10個(gè)贊
面臨同樣的問題。我想問題是當(dāng)“應(yīng)用程序”注冊 Dash 應(yīng)用程序時(shí)當(dāng)前用戶尚未初始化。很好的解決方法,雖然看起來有點(diǎn)不安全,因?yàn)?Flask 會(huì)話只是被編碼的。
https://github.com/RafaelMiquelino/dash-flask-login/blob/master/app.py - 我認(rèn)為更強(qiáng)大的解決方案。它在回調(diào)中檢查 current_user 并將頁面的內(nèi)容用作輸入,因此在頁面加載時(shí)調(diào)用回調(diào)。如果用戶體驗(yàn)不是問題,您也可以跳過對視圖的保護(hù)。
這是我如何使用它的簡化示例:
@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 ''
添加回答
舉報(bào)