0

我有一个关于flask_admin的错误,当我通过在我自己的类名UserDeleteView中从flask_admin.contrib.sqla继承ModelView类来创建自己的模型视图时,当我在UserDeleteView中使用current_user(flask_login的变量)时它给出None但是当我使用它在 UserDeleteView 的任何功能中都可以正常工作

就像我在 UserDeleteView 类的 is_accessable 函数中使用它一样,但是当我在 UserDeleteView 类的 if 中使用它时,它不起作用

这是我的 flask_admin 代码:-

class UserDeleteView(ModelView):

    def is_accessible(self):
        return "User" in {i.split()[0] for i in current_user.permissions() }

    if "User w" not in current_user.permissions():
        can_delete=False


class PostVarificationView(BaseView):
    @expose("/")
    def index(self):
        return self.render('admin/post_varification.html')

class MyAdminIndexView(AdminIndexView):
    def is_accessible(self):
        return (current_user.is_authenticated and len(current_user.permissions())!=0)

admin = Admin(app,index_view=MyAdminIndexView(),name="Microblog")
admin.add_view(UserDeleteView( User, db.session ))
admin.add_view(PostVarificationView(name="Post Varification",endpoint="PostVarification"))

这是我得到的错误:

AttributeError: 'NoneType' object has no attribute 'permissions'

Traceback (most recent call last)
File "/home/chirag/Documents/Projects/microblog1/microblog.py", line 1, in <module>
from app import app,db
File "/home/chirag/Documents/Projects/microblog1/app/__init__.py", line 21, in <module>
from app import routes, models, errors
File "/home/chirag/Documents/Projects/microblog1/app/routes.py", line 309, in <module>
class UserDeleteView(ModelView):
File "/home/chirag/Documents/Projects/microblog1/app/routes.py", line 314, in UserDeleteView
if "User w" not in current_user.permissions():
File "/home/chirag/Documents/Project venv/microblog1/lib/python3.7/site-packages/werkzeug/local.py", line 348, in __getattr__
return getattr(self._get_current_object(), name)
AttributeError: 'NoneType' object has no attribute 'permissions'
4

1 回答 1

0

首次导入模块时执行类主体中定义的代码,current_user因此没有错误。请参阅这个 SO 问题“为什么类的主体在定义时被执行?” 供进一步阅读。

替换can_delete为方法并使用@property 进行装饰,current_user然后可用。

例子:

class UserDeleteView(ModelView):

    def is_accessible(self):
        return "User" in {i.split()[0] for i in current_user.permissions() }

    @property
    def can_delete(self):
        # Your logic here
        return "User w" in current_user.permissions()
于 2019-12-20T11:47:16.693 回答