Home > database >  how to solve the problem with add_url_rule?
how to solve the problem with add_url_rule?

Time:11-13

I can't figure out the problem with the Blueprint class

I decided to use the Blueprint class, I threw in this code

from flask import Flask, Blueprint


app = Flask(__name__)


admin = Blueprint('admin',__name__,template_folder='templates')

app.register_blueprint(admin, url_prefix='/admin')


@admin.route('/',methods=('GET', 'POST'))
def index():
    return 'admin'
    



if __name__ == "__main__":
    app.run(debug=True)

But the address does not exist, and on startup, the terminal displays this

UserWarning: The setup method 'route' can no longer be called on the blueprint 'admin'. It has already been registered at least once, any changes will not be applied consistently.
Make sure all imports, decorators, functions, etc. needed to set up the blueprint are done before registering it.
This warning will become an exception in Flask 2.3.
  @admin.route('/',methods=('GET', 'POST'))
/Users/a-v-tor/Documents/flaskproj/.venv/lib/python3.10/site-packages/flask/scaffold.py:449: UserWarning: The setup method 'add_url_rule' can no longer be called on the blueprint 'admin'. It has already been registered at least once, any changes will not be applied consistently.
Make sure all imports, decorators, functions, etc. needed to set up the blueprint are done before registering it.
This warning will become an exception in Flask 2.3.
  self.add_url_rule(rule, endpoint, f, **options)
/Users/a-v-tor/Documents/flaskproj/.venv/lib/python3.10/site-packages/flask/blueprints.py:490: UserWarning: The setup method 'record' can no longer be called on the blueprint 'admin'. It has already been registered at least once, any changes will not be applied consistently.
Make sure all imports, decorators, functions, etc. needed to set up the blueprint are done before registering it.
This warning will become an exception in Flask 2.3.
  self.record(

According to the docks, in theory, I have a working version ... I tried without a decorator through add_url_rule, but all in vain, I don’t know what to do. Flask version 2.2.2

CodePudding user response:

Your app is registering the blueprint multiple times. here is your fix:

from flask import Flask, Blueprint
admin = Blueprint('admin',__name__,template_folder='templates')

def create_app():
    app = Flask(__name__)
    app.register_blueprint(admin)
    return app

@admin.route('/',methods=('GET', 'POST'))
def index():
    return 'admin'
    
if __name__ == "__main__":
    app = create_app()
    app.run(debug=True)
  • Related