Issue
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
Solution
You must understand that for one application you must use one login manager no matter how many blueprints you use (of course there can be specific exceptions for example when blueprints are 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.
Answered By - tbicr
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.