Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Registering route on blueprint raises AttributeError: 'function' object has no attribute 'route'

Tags:

python

flask

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'
like image 427
George J Padayatti Avatar asked Apr 22 '16 15:04

George J Padayatti


2 Answers

For me this happened when name of route and name of function was same. It seems to be a bug in Flask.

@train.route('/train',methods=['GET'])
def train():
    pass

I changed this to :

@train.route('/train',methods=['GET'])
def something_else():

and Flask was happy then.

like image 118
user1501382 Avatar answered Oct 24 '22 16:10

user1501382


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
like image 39
davidism Avatar answered Oct 24 '22 14:10

davidism