【发布时间】:2013-01-25 10:50:13
【问题描述】:
我有一个未登录的模块/蓝图 welcome 和一个已登录的蓝图 home。我希望具有有效会话的用户转到home.index,并希望作为客人的用户转到welcome.index。但是,我遇到了问题,因为这两个函数都路由到同一个 URL,/。
我怎样才能使这个功能成为可能?我已经尝试添加:
if(logged_in():
redirect(url_for('home.index'))
到欢迎蓝图中的index(),但这当然只会导致循环重定向,因为home.index 的URL 与welcome.index 相同。
我还尝试仅在 logged_in() 为真时定义 welcome.index。但是,这会导致问题,因为站点上还有其他链接指向 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()
编辑 #2:蓝图代码
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"
【问题讨论】:
标签: python routing flask werkzeug