问题描述
我的Flask项目的结构如下:
My Flask project is structured as follows:
my_project
│
├── app
│ ├── __init__.py
│ ├── api
│ ├── static
│ └── templates
├── config.py
└── run.py
app/__ init __.py :
from flask import Flask
app = Flask(__name__)
app.config.from_object('config')
run.py
from app import app
app.run(
host=app.config.get('HOST', '0.0.0.0'),
port=app.config.get('PORT', 5000)
)
以前可行,但是我试图将我的项目从Python 2迁移到Python 3,并且运行python run.py
不再有效.我收到以下错误:
This worked before, but I'm trying to migrate my project from Python 2 to Python 3, and running python run.py
no longer works. I get the following error:
Traceback (most recent call last):
File "/Users/rasmi/Projects/my_project/run.py", line 3, in <module>
app.run(
AttributeError: module 'app' has no attribute 'run'
如果我更改了run.py
中的导入样式以匹配这里:
If I change the import style in run.py
to match the one here:
from .app import app
app.run(
host=app.config.get('HOST', '0.0.0.0'),
port=app.config.get('PORT', 5000)
)
我收到另一个错误:
Traceback (most recent call last):
File "/Users/rasmi/Projects/my_project/run.py", line 1, in <module>
from .app import app
ModuleNotFoundError: No module named '__main__.app'; '__main__' is not a package
在if __name__ == '__main__':
块中包装我的app.run()
调用会产生相同的结果.是什么引起了这个问题?
Wrapping my app.run()
call in an if __name__ == '__main__':
block yields the same results. What's causing this issue?
推荐答案
我通过将app
目录重命名为其他名称(例如webapp
)来解决此问题.使用from webapp import app
可以解决问题.这似乎是因为程序包目录名称在导入时优先于模块名称.也许使用__path__
可以解决这个问题.
I fixed this issue by renaming the app
directory to something else (e.g. webapp
). Using from webapp import app
does the trick. This seems to be because package directory names take precedence over module names when importing. Perhaps using __path__
would allow one to get around this.
这篇关于Flask AttributeError:模块"app"没有属性"run"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!