2 回答
TA贡献1848条经验 获得超2个赞
我在实施它时遇到了同样的问题。@basic_auth.required 装饰器不起作用。相反,我们必须调整几个flask_admin 类以使其与BasicAuth 兼容。在参考了数十个资源后,这是我成功实施的方法!
只是提到我正在使用:Python 3.6.9,Flask==1.1.1,Flask-Admin==1.5.4,Flask-BasicAuth==0.2.0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin, AdminIndexView
from flask_admin.contrib.sqla import ModelView
from flask_basicauth import BasicAuth
from werkzeug.exceptions import HTTPException
app = Flask(__name__)
db = SQLAlchemy(app)
basic_auth = BasicAuth(app)
class Module(db.Model):
__tablename__='Modules'
name = db.Column(db.String(30), unique=True, nullable=False)
"""
The following three classes are inherited from their respective base class,
and are customized, to make flask_admin compatible with BasicAuth.
"""
class AuthException(HTTPException):
def __init__(self, message):
super().__init__(message, Response(
"You could not be authenticated. Please refresh the page.", 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'} ))
class MyModelView(ModelView):
def is_accessible(self):
if not basic_auth.authenticate():
raise AuthException('Not authenticated.')
else:
return True
def inaccessible_callback(self, name, **kwargs):
return redirect(basic_auth.challenge())
class MyAdminIndexView(AdminIndexView):
def is_accessible(self):
if not basic_auth.authenticate():
raise AuthException('Not authenticated.')
else:
return True
def inaccessible_callback(self, name, **kwargs):
return redirect(basic_auth.challenge())
admin = Admin(app, index_view=MyAdminIndexView())
admin.add_view(MyModelView(Module, db.session))
TA贡献1785条经验 获得超4个赞
在官方文件说,有它实施只是为了你的管理页面没有简单的方法。但是,我找到了一种解决方法。您可能需要修改flask 中的一些现有类以使其与基本身份验证兼容。将这些添加到您的代码中。仅供参考,您需要从烧瓶中导入响应。
class ModelView(sqla.ModelView):
def is_accessible(self):
if not basic_auth.authenticate():
raise AuthException('Not authenticated.')
else:
return True
def inaccessible_callback(self, name, **kwargs):
return redirect(basic_auth.challenge())
from werkzeug.exceptions import HTTPException
class AuthException(HTTPException):
def __init__(self, message):
super().__init__(message, Response(
"You could not be authenticated. Please refresh the page.", 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'}
))
然后像这样正常添加管理视图
admin = Admin(app)
admin.add_view(ModelView(Module, db.session))
添加回答
举报