我有一个未登录的模块/蓝图,welcome
和一个登录的蓝图,home
。我想要一个具有有效会话的用户去home.index
,以及一个作为来宾的用户去welcome.index
。但是,我遇到了问题,因为这两个函数都路由到同一个 URL /
,.
我怎样才能使这个功能成为可能?我试过添加:
if(logged_in():
redirect(url_for('home.index'))
toindex()
在欢迎蓝图中,但这当然只会导致循环重定向,因为 URLhome.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()
编辑#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')
模块/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"