python - 在蓝图上注册路由引发 AttributeError : 'function' object has no attribute 'route'

标签 python flask

我在 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/

相关文章:

python-3.x - 在 Flask 中调制 Bokeh 服务器

python - 如何在单元测试中使用 JSON 发送请求

python - Python 列表变量不是通过引用传递的吗?

Python Nose 测试示例

python - 将数组添加到Python中的数据框

python - Flask 中的 import 和 extends 有什么区别?

python - Flask-login 无法登录

python - 属性类和属性装饰器有什么区别

python - 如何从三个数组创建 x、y、z 坐标,其中 x 和 y 使用网格网格生成,z 取决于 x?

python - Flask 循环导入问题 - 将变量从 __init__.py 导入到 View 中