FlaskAppbuilder基于我们更改默认登录页

2024-05-23 14:26:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用FlaskAppBuilder制作一个基本网页。 我想根据登录的用户更改默认登录页 e、 用户1应该被重定向到/home/user1页面,user2应该在登录后登录到/home/general页面等。在

下面是我的自定义索引视图

  class MyIndexView(IndexView):
  index_template = 'index.html'

  @expose('/')
  def main(self):
      return redirect(url_for('AuthDBView.login'))

  @expose('/index')
  def index(self):
      return self.render_template('index.html', message="Welcome to my website")

然后通过调用来启动应用程序

^{pr2}$

我没有看到任何关于如何实现这一点的示例或文档。谢谢你的帮助


Tags: 用户self网页homeindexreturndefhtml
1条回答
网友
1楼 · 发布于 2024-05-23 14:26:33

首先,Flask AppBuilder依赖Flask-login来管理用户,因此您可能需要阅读它的文档。在

除此之外,Flask AppBuilder在每个请求之前将current_user(经过身份验证或匿名)注入Flask的g变量中,因此您所要做的就是从g变量中获取用户并对其进行所需的操作。在

下面是一个IndexView示例,它将匿名用户(未登录)重定向到登录页面。在

如果用户不是一个神经病,并且其名称是John,那么它将被重定向到HomeView.user端点。在

如果它的名称不是John,它将被重定向到HomeView.general端点。在

在索引.py在

from flask import g, url_for, redirect
from flask_appbuilder import IndexView, expose

class MyIndexView(IndexView):

    @expose('/')
    def index(self):
        user = g.user

        if user.is_anonymous:
            return redirect(url_for('AuthDBView.login'))
        else:
            if user.first_name == 'John':
                return redirect(url_for('HomeView.user'))
            else:
                return redirect(url_for('HomeView.general'))

内部视图.py在

^{pr2}$

相关问题 更多 >