装饰器(@need_to_login)似乎在我的代码中不起作用,因为当我打开网页时,它直接进入主页而不是登录页面。这是下面的简单代码。如果有任何明显的错误,请告诉我。我对此很陌生。谢谢
from flask import Flask, render_template, redirect, url_for, request, session, flash
from functools import wraps
app = Flask(__name__)
app.secret_key='nelliville'
def need_to_login(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash('You need to log in first')
return redirect(url_for('login'))
return wrap
@app.route('/login', methods = ['GET', 'POST'])
def login():
error = None
if request.method =='POST':
if request.form['username'] != 'admin' and request.form['password'] != 'admin':
return 'Invalid credentials'
else:
session['logged_in'] = True
return redirect(url_for('home'))
return render_template('login.html', error=error)
@app.route('/')
@need_to_login
def home():
return render_template('home.html')
@app.route('/logout')
@need_to_login
def logout():
session.pop('logged_in', None)
return redirect(url_for('login'))
if __name__ == "__main__":
app.run(debug=True)
答案 0 :(得分:0)
好吧,所以我不能发表评论,因为我没有足够的声誉作为即时通讯新手而引起堆栈溢出。
尝试删除@wraps(f)
need_to_login(f)