Flask注册Blueprint时报'function无register属性'错误是什么原因?
问题原因
你的代码出现了命名覆盖冲突:
- 在
routes_home.py中,你首先将home变量定义为Blueprint实例,后续定义的视图函数又使用了home作为函数名,直接把之前的Blueprint实例覆盖成了函数对象 - 同理
routes_test.py中也存在完全相同的问题:test变量先存储Blueprint实例,后被同名视图函数覆盖
所以调用app.register_blueprint(routes_home.home)时,传入的实际是视图函数而非Blueprint对象,才会抛出function对象没有register属性的报错。
修复方案
修改两个路由文件里的视图函数名,不要和Blueprint实例的变量名重复即可,示例修改如下:
1. 修改routes_home.py
from flask import Blueprint, render_template, abort from jinja2 import TemplateNotFound home = Blueprint('home', __name__) # 视图函数名改为index,不和Blueprint实例名home重复 @home.route('/') def index(): return "<h1>Home</h1>"
2. 修改routes_test.py
from flask import Blueprint, render_template, abort from jinja2 import TemplateNotFound test = Blueprint('test', __name__) # 视图函数名改为test_index,不和Blueprint实例名test重复 @test.route('/test') def test_index(): return "<h1>Test</h1>"
修改后重新运行项目即可正常启动。
内容的提问来源于stack exchange,提问作者appfrosch
相关产品推荐
相关产品推荐

