[英]Flask view raises “AttributeError: 'function' object has no attribute”
app.py
defines a sectors
view that use a Sectors
class defined in sectors.py
. app.py
限定sectors
查看使用一个Sectors
中定义的类sectors.py
。 When I access the view, I get an AttributeError
: 访问视图时,出现
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. 我导入了
sectors
,所以它应该是一个模块,而不是一个函数,并且确实定义了Sectors
。 Why isn't this working? 为什么这不起作用?
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
. 您仍然可以将端点名称保留为
"sectors"
以便与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. 在这两种情况下,导入和函数的名称都是不同的,并且端点名称在两种情况下均保持为
"sectors"
,因此url_for("sectors")
仍然有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.