Flask-Security登录并在菜单栏中注销

时间:2017-01-12 15:44:23

标签: python flask flask-admin

目前,我使用以下代码在Flask-Admin项目的菜单栏上显示登录和注销链接:

if now.weekday() == 5:
    if now.hour == 10 and now.minute == 30:
        webbrowser.open(url)
elif now.hour == 7 and now.minute == 0:
    webbrowser.open(url)

但是,无论当前用户是否登录,都会显示。是否可以在登录时显示注销并在注销时登录?

1 个答案:

答案 0 :(得分:1)

查看Flask-Admin(layout.html)中的菜单模板定义:

{% macro menu_links(links=None) %}
  {% if links is none %}{% set links = admin_view.admin.menu_links() %}{% endif %}
  {% for item in links %}
    {% if item.is_accessible() and item.is_visible() %}
      <li>
        <a href="{{ item.get_url() }}">{{ menu_icon(item) }}{{ item.name }}</a>
      </li>
    {% endif %}
  {% endfor %}
{% endmacro %}

注意{% if item.is_accessible() and item.is_visible() %}行。创建继承的MenuLink类并覆盖is_accessible()is_visible()

示例(未经测试):

from flask_security import current_user

class LoginMenuLink(MenuLink):

    def is_accessible(self):
        return not current_user.is_authenticated 


class LogoutMenuLink(MenuLink):

    def is_accessible(self):
        return current_user.is_authenticated             

admin.add_link(LogoutMenuLink(name='Logout', category='', url="/logout"))
admin.add_link(LoginMenuLink(name='Login', category='', url="/login"))