我正在尝试使用flask-admin限制对管理面板的访问,但出现错误。我也尝试过更改URL名称,但是随后抛出404错误。将flask-admin与ModelView一起使用时,出现以下错误:
异常:无法将具有相同URL和子域的两个Admin()实例分配给同一应用程序。
app / __ init __。py:
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from flask_mail import Mail
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from flask_admin import Admin, BaseView, expose
from flask_admin.contrib.sqla import ModelView
app = Flask(__name__)
app.static_folder = 'templates/static/'
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
bootstrap = Bootstrap(app)
mail = Mail(app)
admin = Admin(app)
if not app.debug:
if app.config['MAIL_SERVER']:
auth = None
if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
secure = None
if app.config['MAIL_USE_TLS']:
secure = ()
mail_handler = SMTPHandler(
mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
fromaddr='no-reply@' + app.config['MAIL_SERVER'],
toaddrs=app.config['ADMINS'], subject='Bhavtaal Failure',
credentials=auth, secure=secure)
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
if not os.path.exists('logs'):
os.mkdir('logs')
file_handler = RotatingFileHandler('logs/bhavtaal.log', maxBytes=10240,
backupCount=10)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)
app.logger.info('Bhavtaal startup')
from app import routes, models, errors
from app.models import User
from app.admin import AdminView
admin = Admin(app, name='Home', index_view=AdminView(User, db.session, url='/admin', endpoint='users_'))
app / admin.py:
from flask_admin.contrib.sqla import ModelView
from flask import session, redirect, url_for, request
class AdminView(ModelView):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.static_folder = 'templates/static/'
def is_accessible(self):
return session.get('user') == 'admin'
def inaccessible_callback(self, name, **kwargs):
if not self.is_accessible():
return redirect(url_for('index.html', next=request.url))
我在删除此行后能够解决此问题:
admin = Admin(app)