简体   繁体   中英

How to add flask-admin to my existing flask

For the past two days I've been trying to intergrate flask-admin to my already existing flask application. But the problem is that I keep getting the same error:

builtins.AssertionError

AssertionError: A name collision occurred between blueprints <flask.blueprints.Blueprint object at 0x000001D8F121B2B0> and <flask.blueprints.Blueprint object at 0x000001D8ECD95A90> . Both share the same name "admin". Blueprints that are created on the fly need unique names.

and that error comes from this block of lines:

Main flask application:

app.route("/admin")
def admin():  
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    return adminScreen.adminPage()

admin.py

def adminPage(): 
    admin=Admin(app)
    admin.add_view(ModelView(User, db.session))
    admin.add_view(ModelView(Role, db.session))
    admin.add_view(ModelView(PointOfSale, db.session))
    return admin

And what I want to do is to manage the users that I already have in my database by using the functions that flask-admin provide.

So my question is; is there a simple way to route flask-admin to my pre-existing flask application?

PS I already know that there is this post from May of 2018 , but I have no idea how to implement the solution that was provided.

In order to use blueprints correctly you should update your app to use app factory instead global variable. Otherwise you cannot have multiple instances of the application. In existing project it may require some work to do but it's worth it. Example factory may looki like this:

def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_pyfile(config_filename)

    from yourapplication.model import db
    db.init_app(app)

    from yourapplication.views.admin import admin
    from yourapplication.views.frontend import frontend
    app.register_blueprint(admin)
    app.register_blueprint(frontend)

    return app

You can find more information here:

http://flask.pocoo.org/docs/1.0/patterns/appfactories/

You don't have to create an app.route("/admin") yourself. That is provided by the built-in blueprint from flask-admin.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM