Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask view raises "AttributeError: 'function' object has no attribute"

Tags:

python

flask

app.py defines a sectors view that use a Sectors class defined in sectors.py. When I access the view, I get an AttributeError:

    sector = sectors.Sectors()
AttributeError: 'function' object has no attribute 'Sectors'
import sectors

@app.route("/sectors")
def sectors():
    sector = sectors.Sectors()
    return render_template('sectors.html', sector=sector)  

I imported sectors, so it should be a module, not a function, and it does have Sectors defined. Why isn't this working?

like image 513
Anon Li Avatar asked Jan 12 '19 14:01

Anon Li


1 Answers

Your view function has the same name as a name you imported earlier. Since the view function is defined after the import in the file, it is what the name points at.

Either alias the import:

import sectors as sectors_mod

@app.route("/sectors")
def sectors():
    sectors_mod.Sectors()
    ...

Or change the name of the function. You can still keep the endpoint name as "sectors" for use with url_for.

import sectors

@app.route("/sectors", endpoint="sectors")
def sectors_view():
    sectors.Sectors()
    ...

In either case, the names of the import and function are distinct, and the endpoint name remains "sectors" in both cases, so url_for("sectors") still works.

like image 68
davidism Avatar answered Nov 15 '22 03:11

davidism