如何处理与多个蓝图的烧瓶登录? [英] How do I handle login in flask with multiple blueprints?

查看:127
本文介绍了如何处理与多个蓝图的烧瓶登录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个蓝图需要集成到一个应用程序。我正在使用 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

  • 您有1个入口点

  • 如果用户未登录,他将重定向到登录/注册页面

  • 您有1个用户加载程序


  • $ b 登录管理器如何工作:
    $ b


    1. 它在请求上下文中注册 current_user
    2. before_request 读取您的会话,获取用户ID,用 user_loader 加载用户,并将其设置为 current_user AnonymousUser

    3. 当您访问私人页面时, login_required 检查 current_user.is_authenticated()其他人重定向到登录页面

    4. 登录时,会话

    因此,您只能初始化一个用于应用程序的登录管理器实例,然后使用 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:

    1. You have 1 entry point
    2. If user is not logged in, he will be redirected to login/registration page
    3. You have 1 user loader

    How login manager works:

    1. It registers current_user in request context
    2. before_request reads your session, gets user id, loads the user with user_loader and set it to current_user or AnonymousUser
    3. When you visit the private page, login_required checks current_user.is_authenticated() else redirects to login page
    4. 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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆