将flask-admin添加到项目时错误的仪表板

use*_*629 11 python flask flask-admin

在此输入图像描述

我正在尝试扩展基于烧瓶的项目https://github.com/hack4impact/flask-base/tree/master/app.这使用app/init.py和蓝图中的应用程序工厂模式.

在app/init.py我有:

import os
from flask import Flask
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_assets import Environment
from flask_wtf import CsrfProtect
from flask_compress import Compress
from flask_rq import RQ
from flask_admin import Admin, BaseView, expose
from flask_admin.contrib.sqla import ModelView
# from app.models import User


from config import config
from .assets import app_css, app_js, vendor_css, vendor_js




basedir = os.path.abspath(os.path.dirname(__file__))

mail = Mail()
db = SQLAlchemy()
csrf = CsrfProtect()
compress = Compress()


# Set up Flask-Login
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'account.login'

from app.models import User


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it


    with app.app_context():
        m =app.url_map

    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)
    # adm = Admin(app, name='MyAPP')
    adm = Admin(endpoint='adminz', name='adz', url='/adminz')



   ......

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .admin import admin as admin_blueprint
    # from .admin import admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    return app
Run Code Online (Sandbox Code Playgroud)

模板/管理/ db.html:

<p>Hello world</p>
Run Code Online (Sandbox Code Playgroud)

对于管理员视图(https://github.com/hack4impact/flask-base/blob/master/app/admin/views.py)我添加了:

from flask_admin import Admin, BaseView, expose
from flask_admin.contrib.sqla import ModelView
from app import adm as adm, db

class MyView(ModelView):
    @expose('/')
    def db(self):
        return self.render('admin/db.html')


# admin management setup
@main.route('/db')
def db():
    adm.add_view(MyView(User, db.session))
Run Code Online (Sandbox Code Playgroud)

当我打开时,我得到的管理仪表板不是flask-admin基本视图:

 127.0.0.1:5000/db
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我究竟做错了什么?

编辑:

按照您的指示,我将create_app更改为以:

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it
    # adm = Admin(name='admin2', endpoint='/db', url='/db', template_mode='bootstrap3',base_template='admin/db.html')


    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)
    adm = Admin(app, name='MyAPP')
    # adm = Admin(endpoint='adminz', name='adz', url='/adminz')
    adm.add_view(MyView(User, db.session, endpoint='db'))
Run Code Online (Sandbox Code Playgroud)

这导致:

在register_blueprint(blueprint,self.blueprints [blueprint.name],blueprint.name)中输入文件".... flask\app.py",第946行.AssertionError:在和之间发生蓝图名称冲突.两者都使用相同的名称"admin".动态创建的蓝图需要唯一的名称.

EDIT2:

到create_app结尾我添加了:

# Create app blueprints
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)

from .account import account as account_blueprint
app.register_blueprint(account_blueprint, url_prefix='/account')

from .admin import admin as admin_blueprint
# from .admin import admin_blueprint
app.register_blueprint(admin_blueprint, url_prefix='/admin')
# app.register_blueprint(admin_blueprint, url_prefix='/ab')

with app.app_context():
    m =app.url_map

return app
Run Code Online (Sandbox Code Playgroud)

我不确定你想看到什么,但是m.rules给出:

 <Rule '/account/manage/change-password' (HEAD, GET, OPTIONS, POST) -> account.change_password>,
 <Rule '/account/manage/change-email' (HEAD, GET, OPTIONS, POST) -> account.change_email_request>,
 <Rule '/account/manage/info' (HEAD, GET, OPTIONS, POST) -> account.manage>,
 <Rule '/account/confirm-account' (HEAD, GET, OPTIONS) -> account.confirm_request>,
 <Rule '/account/reset-password' (HEAD, GET, OPTIONS, POST) -> account.reset_password_request>,
 <Rule '/account/unconfirmed' (HEAD, GET, OPTIONS) -> account.unconfirmed>,
 <Rule '/account/register' (HEAD, GET, OPTIONS, POST) -> account.register>,
 <Rule '/account/logout' (HEAD, GET, OPTIONS) -> account.logout>,
 <Rule '/account/manage' (HEAD, GET, OPTIONS, POST) -> account.manage>,
 <Rule '/account/login' (HEAD, GET, OPTIONS, POST) -> account.login>,
 <Rule '/admin/_update_editor_contents' (OPTIONS, POST) -> admin.update_editor_contents>,
 <Rule '/admin/invite-user' (HEAD, GET, OPTIONS, POST) -> admin.invite_user>,
 <Rule '/admin/new-user' (HEAD, GET, OPTIONS, POST) -> admin.new_user>,
 <Rule '/admin/users' (HEAD, GET, OPTIONS) -> admin.registered_users>,
 <Rule '/get_session_job_value' (HEAD, GET, OPTIONS) -> main.get_session_job_value>,
 <Rule '/cl_confirm_chrome' (HEAD, GET, OPTIONS, POST) -> main.cl_confirm_chrome>,
 <Rule '/render_png' (HEAD, GET, OPTIONS) -> main.render_png>,
 <Rule '/selected' (HEAD, GET, OPTIONS) -> main.selected>,
 <Rule '/cl_dash' (HEAD, GET, OPTIONS, POST) -> main.cl_dash>,
 <Rule '/about' (HEAD, GET, OPTIONS) -> main.about>,
 <Rule '/admin/' (HEAD, GET, OPTIONS) -> admin.index>,
 <Rule '/dash' (HEAD, GET, OPTIONS) -> main.dash>,
 <Rule '/jobs' (HEAD, GET, OPTIONS) -> main.get_jobs>,
 <Rule '/' (HEAD, GET, OPTIONS) -> main.index>,
 <Rule '/account/manage/change-email/<token>' (HEAD, GET, OPTIONS, POST) -> account.change_email>,
 <Rule '/admin/user/<user_id>/change-account-type' (HEAD, GET, OPTIONS, POST) -> admin.change_account_type>,
 <Rule '/admin/user/<user_id>/change-email' (HEAD, GET, OPTIONS, POST) -> admin.change_user_email>,
 <Rule '/admin/user/<user_id>/_delete' (HEAD, GET, OPTIONS) -> admin.delete_user>,
 <Rule '/admin/user/<user_id>/delete' (HEAD, GET, OPTIONS) -> admin.delete_user_request>,
 <Rule '/admin/user/<user_id>/info' (HEAD, GET, OPTIONS) -> admin.user_info>,
 <Rule '/account/join-from-invite/<user_id>/<token>' (HEAD, GET, OPTIONS, POST) -> account.join_from_invite>,
 <Rule '/account/confirm-account/<token>' (HEAD, GET, OPTIONS) -> account.confirm>,
 <Rule '/account/reset-password/<token>' (HEAD, GET, OPTIONS, POST) -> account.reset_password>,
 <Rule '/admin/static/<filename>' (HEAD, GET, OPTIONS) -> admin.static>,
 <Rule '/admin/user/<user_id>' (HEAD, GET, OPTIONS) -> admin.user_info>,
 <Rule '/results/<job_key>' (HEAD, GET, OPTIONS) -> main.get_results>,
 <Rule '/static/<filename>' (HEAD, GET, OPTIONS) -> static>
Run Code Online (Sandbox Code Playgroud)

编辑3:

我不得不说这是一个不可思议的答案!你真的教过我很多东西.我已按照您的指示更换了上述规则的网址.我10天前的原始计划只是使用基本的flask-admin CRUD功能.我对db.html模板不感兴趣(它只是我试过的东西).

无论如何都试图改变管理蓝图的名称(你的号码1).我在尝试将app/admin/init.py更改为:之前尝试过:

from flask import Blueprint
admin = Blueprint('admin_blueprint', __name__)
from . import views  # noqa
Run Code Online (Sandbox Code Playgroud)

现在,当我打开

http://127.0.0.1:5000/adminz/
Run Code Online (Sandbox Code Playgroud)

我收到404错误

最终编辑:

https://chat.stackoverflow.com/users/5819113/diego-quintana解决了这个问题,他解释说创建蓝图的flask-admin与基于烧瓶的管理蓝图之间存在冲突.通过更改蓝图的名称和基于flask的项目的静态文件夹.Flask-admin可以在不被覆盖的情况下工作.请参阅https://github.com/kc1/flask-base

blu*_*onk 6

你应该初始化Admin和注册viewsblueprints在里面create_app.检查这是否适合您.

# app factory
def create_app(config_name):

    # configure current app
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # wrap app with extensions
   ...

    # admin.init_app(app) does not work and flask-admin
    # should be instantiated inside create_app()
    # see https://github.com/flask-admin/flask-admin/issues/910#issuecomment-115003492
    # for details
    admin = Admin(app, name='MyAPP')

    ...

    # import models 
    from .models.user import User
    # more imports happening here

    # import flask-admin views to be used in the admin panel
    from .admin.views import MyView


    # register admin view forms
    admin.add_view(MyView(name='MyCustomView', endpoint='db'))

    # register blueprints
    # ...

    # implementation of the app factory pattern
    return app
Run Code Online (Sandbox Code Playgroud)

编辑:

我认为正在发生的是

  • 回购中的应用程序已经有一个名为adminliving in/admin 的蓝图
  • 您想flask-admin在应用程序中实现,但它与现有蓝图冲突

你可以做两件事:

  1. blueprint将repo中的当前名称更改为与之不同的名称admin,因为flask-admin它与之冲突.(从您的github问题中读取它似乎是很多硬编码的内部admin.static,这使得更改当前的admin蓝图更容易.

蓝图的解剖有点像这样

# app/myblueprint/__init__.py
from flask import Blueprint

# a random blueprint
myblueprint = Blueprint(name='mycustomblueprint', 
                         import_name=__name__, # name of the file
                         static_folder='static', # a folder inside app/myblueprint/static
                         template_folder='templates', # a folder inside app/myblueprint/templates
                         static_url_path='/static', # this is what mycustomblueprint.static will point to, and if the name is admin it will be admin.static, thus colliding with flask-admin
                         url_prefix='/myblueprintprefix', # this will be appended to each view inside your blueprint, i.e. a view '/foo' will get converted into '/myblueprintprefix/foo' in your url mappings
                         subdomain=None,
                         url_defaults=None,
                         root_path=None)

from . import views # import the views inside app/myblueprint/views.py
Run Code Online (Sandbox Code Playgroud)

然后,您导入这里面create_app作为

from .myblueprint import myblueprint as my_blueprint
app.register_blueprint(my_blueprint) # notice I've defined url_prefix in the Blueprint definition. You can do it at registration time, it's up to you
Run Code Online (Sandbox Code Playgroud)

tl; dr:改变admin蓝图,因为它与之发生冲突flask-admin

  1. flask-admin基于视图工作,生成管理视图的模式是通过导入它们并传递一个url附加到/admin端点(flask-admin生命中)的参数.在这种情况下,你可以想到两种口味(更多,但为了示例,它没关系)
    • ModelView,用于创建自定义CRUD视图并同时获取a modeldb.session对象.
    • BaseView用于扩展其使用的admin蓝图内的通用视图flask-admin.

这意味着,如果要db.htmlflask-admin视图中呈现自己的文件,则必须执行以下操作:

# app/modelviews/mycustomviews.py
from flask_admin import BaseView, expose

class DBView(BaseView): # notice I'm using BaseView and not ModelView
    @expose('/')
    def index(self):
        return self.render('modelviews/db.html') # this file should live in app/templates/modelviews/db.html
Run Code Online (Sandbox Code Playgroud)

在里面 create_app

# register admin view forms
from .modelviews import DBView
admin.add_view(DBView(name='MyCustomView', endpoint='db')) # this will show up in your `flask-admin` main view as MyCustomView, and it will live in {host}/admin/db
Run Code Online (Sandbox Code Playgroud)

您还可以在您url_map拥有的上下文中检查烧瓶应用程序的参数.你不需要这一点create_app

with app.app_context():
m =app.url_map
Run Code Online (Sandbox Code Playgroud)

我提到它是因为它可以帮助你在python中调试你的视图repl.导入您的应用,并按照我提供的要点.本url_map应该返回类似的列表<Rules>

 [<Rule '/admin/' (OPTIONS, HEAD, GET) -> admin.index>,
 <Rule '/admin/db' (OPTIONS, HEAD, GET) -> dbview.index>]
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以确认您的视图位于应有的位置.希望这可以帮助.