Answer a question

I define a blueprint in app/settings/__init__.py, then import the views to register them. This raises AttributeError: 'function' object has no attribute 'route'. Why am I getting this error and how do I fix it?

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'

Answers

Your views module has a view function named "settings", which shadows the imported blueprint named "settings" once execution reaches it.

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():
    ...

Alias the import to use a different name that won't collide with your view function names.

from app.settings import settings as bp

@bp.route('/')
def settings():
    pass
Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐