I am trying to wrap my head around blueprints in Flask. I started a minimal app to try and see how the setup should be, but I am getting an error when I try to run the app.
I have a venv
with Python 3.9 and the following path values:
PYTHONUNBUFFERED=1;FLASK_ENV=development;FLASK_APP=app.py
Here's the code:
app.py
from flask import Flask
import routes_home
import routes_test
app = Flask(__name__)
app.register_blueprint(routes_home.home)
app.register_blueprint(routes_test.test)
if __name__ == "__main__":
app.run(port=5000)
routes_home.py:
from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound
home = Blueprint('home', __name__)
@home.route('/')
def home():
return "<h1>Home</h1>"
routes_test.py
from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound
test = Blueprint('test', __name__)
@test.route('/test')
def test():
return "<h1>Test</h1>"
And here's the abbreviated traceback:
File "/Users/asseeger/CloudStation/appfros.ch/dev/so-samples/py-blueprints/app.py", line 7, in <module>
app.register_blueprint(routes_home.home)
File "/Users/asseeger/CloudStation/appfros.ch/dev/so-samples/py-blueprints/venv/lib/python3.9/site-packages/flask/scaffold.py", line 56, in wrapper_func
return f(self, *args, **kwargs)
File "/Users/asseeger/CloudStation/appfros.ch/dev/so-samples/py-blueprints/venv/lib/python3.9/site-packages/flask/app.py", line 1030, in register_blueprint
blueprint.register(self, options)
AttributeError: 'function' object has no attribute 'register'
What am I doing wrong here?
CodePudding user response:
The code suffers from naming confusion in this bit:
home = Blueprint('home', __name__)
@home.route('/')
def home():
return "<h1>Home</h1>"
Here, home
start life as a Blueprint, then becomes a function. The last binding wins.
app.register_blueprint(routes_home.home)
then attempts to register a function instead of a Blueprint. This is what
'function' object has no attribute 'register'
at the end of the stack trace hints at.
One way forward is to rename the first use to
home_bp = Blueprint('home', __name__)
(and propagate that name). The other is to rename the function. Your call as to which is clearer to your eye.