2 回答

TA貢獻1848條經(jīng)驗 獲得超2個贊
我在實施它時遇到了同樣的問題。@basic_auth.required 裝飾器不起作用。相反,我們必須調(diào)整幾個flask_admin 類以使其與BasicAuth 兼容。在參考了數(shù)十個資源后,這是我成功實施的方法!
只是提到我正在使用:Python 3.6.9,F(xiàn)lask==1.1.1,F(xiàn)lask-Admin==1.5.4,F(xiàn)lask-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條經(jīng)驗 獲得超4個贊
在官方文件說,有它實施只是為了你的管理頁面沒有簡單的方法。但是,我找到了一種解決方法。您可能需要修改flask 中的一些現(xiàn)有類以使其與基本身份驗證兼容。將這些添加到您的代碼中。僅供參考,您需要從燒瓶中導入響應(yīng)。
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))
添加回答
舉報