我想使用flask-admin设置一个基本的管理界面,我希望所有这些都可以放在蓝图中。这是我的代码的最小版本:
#app.py
from flask import Flask
from bp import bp
app = Flask(__name__)
app.register_blueprint(bp)
if __name__ == "__main__":
app.run(debug=True)
#bp.py
from flask import Blueprint, current_app
from flask_admin import Admin
from flask_admin.contrib.pymongo import ModelView
import pymongo
conn = pymongo.MongoClient()
bp = Blueprint('bp', __name__,
template_folder='templates')
admin = Admin(current_app)
admin.add_view(ModelView(conn.my_db.my_collection))
运行python app.py
时,它会与RuntimeError: working outside of application context
一起崩溃,因为admin
绝不会被bp
挂钩(或用于描述它的任何词语)@bp.route('/<page>')
def show(page):
pass
。
通常,人们会写
Admin
但是我在创建admin = Admin()
对象的上下文中找不到合适的装饰器。我尝试过的一件事是bp.py
中的admin
,app.py
中的admin.app = app
,app.py
中的.intern()
。这有效,但感觉就像我在几个文件中分裂逻辑,所以我对此并不十分满意。处理这种情况的pythonic方法是什么?
答案 0 :(得分:1)
您需要实际的app对象来初始化Flask管理员类。 Current_app不起作用。此调用应放在app.py上。然后在蓝图上你可以使用
from app import admin
答案 1 :(得分:0)
以这种方式解决。仅供参考。
#YourApp/init.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin
db = SQLAlchemy()
admin = Admin(name='TuozhanOA', template_mode='bootstrap3')
def create_app(config_class=Config):
app = Flask(name)
app.config.from_object(Config)
db.init_app(app)
admin.init_app(app)
from YourApp.main.routes import main
app.register_blueprint(main)
from YourApp.adminbp.routes import adminbp, user_datastore
app.register_blueprint(adminbp)
security = Security(app, user_datastore)
return app
#YourApp/adminbp/routes.py
from flask import render_template, Blueprint
from YourApp.models import User, Role
from YourApp import db, admin
from flask_admin.contrib.sqla import ModelView
from wtforms.fields import PasswordField
from flask_admin.contrib.fileadmin import FileAdmin
import os.path as op
from flask_security import current_user, login_required, RoleMixin, Security,
SQLAlchemyUserDatastore, UserMixin, utils
adminbp = Blueprint('adminbp', name)
admin.add_view(ModelView(User, db.session, category="Team"))
admin.add_view(ModelView(Role, db.session, category="Team"))
path = op.join(op.dirname(file), 'tuozhan')
admin.add_view(FileAdmin(path, '/static/tuozhan/', name='File Explore'))