我在 app/settings/__init__.py
中定义了一个蓝图,然后导入 View 以注册它们。这引发了 AttributeError: 'function' object has no attribute 'route'
。为什么会出现此错误以及如何解决?
from flask import Blueprint
settings = Blueprint('settings', __name__, template_folder='templates')
from app.settings import views
Traceback (most recent call last):
File "E:/surfmi/run.py", line 1, in <module>
from app import app
File "E:\surfmi\app\__init__.py", line 34, in <module>
from app.settings import settings
File "E:\surfmi\app\settings\__init__.py", line 6, in <module>
from app.settings import views
File "E:\surfmi\app\settings\views.py", line 17, in <module>
@settings.route('/general')
AttributeError: 'function' object has no attribute 'route'
最佳答案
您的 View 模块有一个名为“settings”的 View 函数,一旦执行到它就会隐藏名为“settings”的导入蓝图。
from app.settings import settings
# the name settings refers to the blueprint imported above
@settings.route('/a')
def this_works():
...
# the name settings refers to the blueprint imported above
@settings.route('/')
def settings():
...
# the name settings now refers to the function defined above
@settings.route('/b')
def this_fails():
...
为导入设置别名以使用不会与您的 View 函数名称冲突的不同名称。
from app.settings import settings as bp
@bp.route('/')
def settings():
pass
关于python - 在蓝图上注册路由引发 AttributeError : 'function' object has no attribute 'route' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36798380/