Running a Flask blueprint from the program

Issue

I’m having problems with running my Flask application with a blueprint from the Python program. Here’s what my code is and what I’ve tried.

from flask import Blueprint, render_template
from flask_login import login_required, current_user

main = Blueprint('main', __name__)

@main.route('/')
def index():
    return render_template('index.html')

@main.route('/profile')
@login_required
def profile():
    return render_template('profile.html', name=current_user.name)

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

But my code throws the error AttributeError: 'Blueprint' object has no attribute 'run'

Solution

You can’t run a blueprint directly, it should be imported into your main app and registered. Then, the main app will run, check the official flask documentation here.

Here is what you should do:

from flask import Flask
from yourapplication.mainblueprint import main

app = Flask(__name__)
app.register_blueprint(main)

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

Also, you can remove the if __name__ == '__main__' block from your blueprint, it won’t be necessary.

Answered By – Magnun Leno

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published