如何处理与多个蓝图的烧瓶登录? [英] How do I handle login in flask with multiple blueprints?
问题描述
flask-login
来处理登录。然而,我很困惑如何处理蓝图的 LoginManager()
和 .user_loader
。 这是我当前的文件结构。
system /
run .py
config.py
app /
__init__.py
models.py
views /
blueprint1.py
blueprint2.py
static /
模板/
<模板>
实现它们的正确方法是什么?我只是在 __ init __。py
处调用它们,并在蓝图中导入登录管理器变量?或者我需要在蓝图中单独调用它们?
希望我能够清楚地描述问题。感谢您的阅读和回答。您必须明白,对于一个应用程序,您必须使用一个登录管理器,而不管如何匹配蓝图使用(当然,当蓝图独立时,可以有特定的例外,但在这种情况下,您可能不能使用 flask-login
)。因为:
$ b $ ol
$ b 登录管理器如何工作:
$ b
- 它在请求上下文中注册
current_user
-
before_request
读取您的会话,获取用户ID,用user_loader
加载用户,并将其设置为current_user
或AnonymousUser
- 当您访问私人页面时,
login_required
检查current_user.is_authenticated()
其他人重定向到登录页面 - 登录时,会话
因此,您只能初始化一个用于应用程序的登录管理器实例,然后使用 login_required
和 current_user
。
I have multiple blueprints that needs to be integrated into a single app. I'm using flask-login
to handle logins. However I'm confused on how to handle the LoginManager()
and the .user_loader
for my blueprints.
This is my current file structure.
system/
run.py
config.py
app/
__init__.py
models.py
views/
blueprint1.py
blueprint2.py
static/
templates/
<templates>
What's the correct way to implement them? Do I just call them at the __init__.py
and import the login manager variable at the blueprints? or Do I need to call them individually in the blueprints?
Hopefully I'm able to portray the question clearly. Thank you for reading and answering
You must understand that for one application you must use one login manager no matter how match blueprint you use (of course there are can be specific exceptions for example when blueprints independent, but in this case you probably can't use flask-login
). Because:
- You have 1 entry point
- If user is not logged in, he will be redirected to login/registration page
- You have 1 user loader
How login manager works:
- It registers
current_user
in request context before_request
reads your session, gets user id, loads the user withuser_loader
and set it tocurrent_user
orAnonymousUser
- When you visit the private page,
login_required
checkscurrent_user.is_authenticated()
else redirects to login page - On login, it adds user id to the session
So you must initialize only one login manager instance for flask application and then use login_required
and current_user
in all your blueprints.
这篇关于如何处理与多个蓝图的烧瓶登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!