Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-Appbuilder change the default landing page based on user

I am using Flask App builder to make a basic webpage. I want to change the default landing page based on the user logged in e.g. user1 should be redirected to /home/user1 page and user2 should login to /home/general page etc after they logged in.

Below is my custom index view

  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")

and starting the app by calling

appbuilder = AppBuilder(app, db.session, indexview=MyIndexView)

I have not seen any example or documentation on how to achieve this. so appreciate any help

like image 956
Linus Avatar asked Dec 18 '22 08:12

Linus


1 Answers

First off all, Flask-AppBuilder depends on Flask-login to manage users so you might want to read its documentation.

Besides that, Flask-AppBuilder injects the current_user(authenticated or anonymous) in Flask's g variable before each request, so all you have to do is get the user from g variable and do what you want with it.

Below is an example of an IndexView that redirects anonymous users(not logged in) to the login page.

If the user is not anonynous and its name is John, it is redirected to the HomeView.user endpoint.

If its name is not John, it is redirected to the HomeView.general endpoint.

index.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'))

Inside views.py

class HomeView(BaseView):
    route_base = "/home"

    @expose('/user/')
    def user(self):
        greeting = "Hello John"
        return self.render_template('logged_user.html', greeting=greeting)


    @ expose('/general/')
    def general(self):
        greeting = "Hello ordinary user"
        return self.render_template('logged_user.html', greeting=greeting)

appbuilder.add_view_no_menu(HomeView())
like image 177
Serafim Avatar answered Jan 18 '23 22:01

Serafim