我尝试使用Flask-login管理用户会话,但我一直陷入困境。
login_manager = LoginManager()
login_manager.init_app(app)
class User(UserMixin):
def __init__(self, id, is_active, urole = "admin"):
self.id = id
self.is_active = is_active
self.urole = urole
def is_active(self):
return self.is_active
def activate_user(self):
self.is_active = True
def get_id(self):
return self.id
def get_urole(self):
return self.urole
@login_manager.user_loader
def load_user(user_id):
print(user_id)
return dict_users.get(user_id)
上面是我创建的User
类和load_user
函数。
现在在我的validate
函数中,正在执行此操作,
if models.validateLogin(stripeName, stripePassword) == True:
end_time = time.time()
outputJSON = "{'error':" + str(False) + ",'message':" + str("Login Successful") + ",'time':" + str(
end_time - start_time) + "}"
session['logged_in'] = True
session['username'] = stripeName
logged_in_user = User(5,session['logged_in'])
print(logged_in_user.__dict__)
login_user(logged_in_user)
return redirect(url_for("home"))
logged_in_user.__dict__
的print语句给出了以下输出
{'id': 5, 'is_active': True, 'urole': 'admin'}
(P.S。我将id硬编码为5,用于测试目的。)
但之后我一直收到以下错误,
line 31, in get_id
return self.id
AttributeError: 'int' object has no attribute 'id'
此外,在load_user(user_id):
函数中,我为user_id
添加了一个print语句,它似乎打印了正在添加的用户的id。感觉,User
没有被添加到它或类似的东西,或只是把id
即5作为参数。
我错过了什么?
编辑:
添加了全局字典
global dict_users
dict_users = {}
登录后更新了主要功能中的dict_users
。
dict_users = logged_in_user
在logout
函数
@app.route('/logout', methods=['POST', 'GET'])
def logout_dashboard():
if request.method == 'POST':
session['logged_in'] = False
session['username'] = ""
dict_users = {}
return redirect(url_for('login'))
但现在,每当我尝试使用login_required
之类的网址时
@app.route('/abc', methods=['GET', 'POST'])
@login_required
def abc():
if request.method == 'POST' or request.method == 'GET':
return render_template('home.html', value=session['username'])
我遇到错误。
Unauthorized
The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn't understand how to supply the credentials required.