我有一个未登录的模块/蓝图,welcome
和登录的蓝图home
。我希望具有有效会话的用户转到home.index
,以及作为访客的用户转到welcome.index
。但是,我遇到了问题,因为这两个函数都路由到同一个网址/
。
如何使此功能成为可能?我试过添加:
if(logged_in():
redirect(url_for('home.index'))
欢迎蓝图中的到index()
,但这当然只会导致循环重定向,因为home.index
的网址与welcome.index
相同。
如果welcome.index
为真,我还尝试定义logged_in()
。但是,这会导致问题,因为网站上有其他链接指向welcome.index
,如果用户已登录,则会导致错误,因为welcome.index
在技术上已不再存在。
我在此代码中看到此错误AttributeError: 'Blueprint' object has no attribute 'index'
:
from flask import Flask, session, g
from modules.welcome import welcome
from modules.home import home as home
from modules.home import index
from modules.welcome import index
app = Flask(__name__)
app.config.from_pyfile('config.cfg')
app.register_blueprint(welcome)
app.register_blueprint(home)
@app.route('/', methods=['GET', 'POST'])
def index():
if 'user_id' in session:
return home.index()
else:
return welcome.index()
modules / home.py中的代码:
from flask import Blueprint, render_template, redirect, url_for, request, session, g
from models.User import User
from helpers.login import *
home = Blueprint('home', __name__)
def index():
return render_template('home/index.html')
modules / welcome.py中的代码:
from flask import Blueprint, render_template, redirect, url_for, request, session, g
import md5
from models.User import User
from helpers.login import *
welcome = Blueprint('welcome', __name__)
def index():
alert, email = None, None
if request.method == 'POST' and not logged_in():
email = request.form['email']
password_salt = md5.new(request.form['password']).hexdigest()
user = User.query.filter_by(email=email , password_salt=password_salt).first()
if user is None:
alert = "Wrong username or password!"
else:
session['user_id'] = user.id
return redirect(url_for('home.index'))
return render_template('welcome/index.html', alert=alert, email=email)
@welcome.route('/about')
def about():
return render_template('welcome/about.html')
@welcome.route('/tandp')
def tandp():
return render_template('welcome/tandp.html')
@welcome.route('/logout')
def logout():
session.pop('user_id', None)
return redirect(url_for('welcome.index'))
@welcome.route('/register')
def register():
error = None
return "HI"
答案 0 :(得分:3)
拆分你的方法,测试记录状态,然后调用正确的函数(在每个函数上添加你需要的参数):
from ????? import app
from ????? import logged_in
import home.index
import welcome.index
@app.route('/')
def your_basic_index_view():
if logged_in():
return home.index()
else:
return welcome.index()
或者对装饰者做同样的事情。您将无法使用有条件地指向两个不同视图的单个路径。
修改强>
尝试以下方法:
from flask import Flask, session, g
from modules.welcome import welcome
from modules.home import home as home
from modules.home import index as h_index
from modules.welcome import index as w_index
app = Flask(__name__)
app.config.from_pyfile('config.cfg')
app.register_blueprint(welcome)
app.register_blueprint(home)
@app.route('/', methods=['GET', 'POST'])
def index():
if 'user_id' in session:
return h_index()
else:
return w_index()