[英]Can't get session variables from a different Flask Blueprint
I am trying to use Flask Blueprints, but it seems I can't access session object in the different Blueprints.我正在尝试使用 Flask 蓝图,但似乎我无法在不同的蓝图中访问 session object。
In an Authentication Blueprint I have the following function:在身份验证蓝图中,我有以下 function:
@authentication_bp.route("/login", methods=["POST"])
def login():
# Get information about user and try to find him
username = request.get_json().get("username")
password = request.get_json().get("password")
user = User.find_by_username(username)
# Validate user
if not user or not user.verify_password(password):
error_log.error("Login failed!")
return jsonify(success=False, message="Incorrect username or password!"), 403 # forbidden
# Update session
session["LOGGED_IN"] = True
session["USERNAME"] = username
info_log.info("%s logged in successfully." % username)
return jsonify(success=True)
So if the user successfully signs in, session should be updated.所以如果用户成功登录,session 应该被更新。
The in main.py I have a checkLogin function:在 main.py 我有一个 checkLogin function:
@app.route("/checkLogin")
def check_login():
print(session.get("LOGGED_IN"))
# Check if there is a user logged in
if session.get("LOGGED_IN"):
return jsonify(logged_in=True)
return jsonify(logged_in=False)
I run check_login() right after login().我在 login() 之后立即运行 check_login()。 Login() function returns 'success' but after that
print(session.get("LOGGED_IN"))
prints None
, rather than True
. Login() function 返回 'success' 但之后
print(session.get("LOGGED_IN"))
打印None
,而不是True
。
Is this behaviour of Blueprints expected and how could I achieve what I want?蓝图的这种行为是预期的吗?我怎样才能实现我想要的?
NOTE: I checked out Flask Blueprint Putting something on session but that didn't answer the question for me.注意:我检查了Flask 蓝图在 session 上放置了一些东西,但这并没有回答我的问题。
NOTE: I have imported session in both files and I have set the secret key for the Flask app.注意:我在两个文件中都导入了 session 并且我已经为 Flask 应用程序设置了密钥。
So after some thinking I realised that I don't store a lot of information in the session - only isLoggedIn (boolean) and username (string).所以经过一番思考,我意识到我没有在 session 中存储很多信息 - 只有 isLoggedIn (布尔值)和用户名(字符串)。 I decided to create a separate class called ActiveUser storing those variables and I imported it where needed.
我决定创建一个名为 ActiveUser 的单独 class 来存储这些变量,并在需要的地方导入它。 I am not really sure if this is a proper solution or just a workaround though.
我不确定这是一个正确的解决方案还是只是一种解决方法。
It is better to use Flask-Login extension because Flask sessions are not secure.最好使用 Flask-Login 扩展,因为 Flask 会话不安全。 You can read more about this here: https://blog.miguelgrinberg.com/post/how-secure-is-the-flask-user-session
您可以在此处阅读有关此内容的更多信息: https://blog.miguelgrinberg.com/post/how-secure-is-the-flask-user-session
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.