【问题标题】:flask-admin "AdminIndexView" not working to restrict the /admin pageflask-admin "AdminIndexView" 无法限制 /admin 页面
【发布时间】:2021-09-24 04:36:44
【问题描述】:

这是我在stackoverflow中的第一个问题。

我需要更改 flask_admin 的默认页面,但它不起作用,我想让非管理员用户无法访问它...

管理文件:

from flask import redirect, url_for
from flask_admin import AdminIndexView
from flask_admin.contrib.sqla import ModelView
from flask_login import current_user
from wtforms.fields import FileField
from wtforms.validators import DataRequired

from . import adm, db
from .models import User, Product


def configure():
    adm.index_view = IndexAdmin()

    adm.add_view(UserAdmin(User, db.session))
    adm.add_view(ProductsAdmin(Product, db.session))


class IndexAdmin(AdminIndexView):
    def is_accessible(self):
        return current_user.is_authenticated and current_user.admin

    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for("views.home_page"))


class UserAdmin(ModelView):
    form_excluded_columns = ["created_date", "updated_date", "products", "adresses"]
    column_exclude_list = ["password", "phone", "money"]
    column_searchable_list = ["email"]

    def is_accessible(self):
        return current_user.is_authenticated and current_user.admin

    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for("admin.index"))


class ProductsAdmin(ModelView):
    form_excluded_columns = ["created_date", "updated_date", "user_products"]
    column_exclude_list = ["image"]

    column_type_formatters = {"image": FileField(label="Image", validators=[DataRequired()])}

    def is_accessible(self):
        return current_user.is_authenticated and current_user.admin

    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for("admin.index"))

我试图这样做以限制页面,但这不起作用...

class IndexAdmin(AdminIndexView):
    def is_accessible(self):
        return current_user.is_authenticated and current_user.admin

    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for("views.home_page"))

【问题讨论】:

    标签: flask flask-admin


    【解决方案1】:

    我不确定这是不是差距,但官方文档不建议像 adm.index_view = 那样设置它。相反,https://flask-admin.readthedocs.io/en/latest/api/mod_base/#default-view 建议:

    admin = Admin(index_view=MyHomeView())
    

    因此,一种可能性是 Admin() 的 init 进程对 index_view 做了一些在您直接设置时不会发生的事情。

    文档 (https://flask-admin.readthedocs.io/en/latest/api/mod_base/#flask_admin.base.Admin.init_app) 还表明您可以使用 init_app 来延迟此操作,这是我以前使用过的方式。比如:

    admin.init_app(app, index_view= MyHomeView())
    

    【讨论】:

    • 谢谢你,我只需要在 init_app 中做这个 admin.init_app(app, index_view= MyHomeView()) !
    • 很高兴听到!这里习惯性地单击解决问题的答案旁边的复选标记。 (这有助于其他回答者看到您的问题已得到解决,并且有相同问题的其他人可以更快地找到一个好的答案。)
    猜你喜欢
    • 2014-12-22
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 2018-08-11
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    相关资源
    最近更新 更多