Python Flask - 导入错误:没有名为 app 的模块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22711087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask - ImportError: No module named app
提问by onepiece
First I created __init__.py
首先我创建 __init__.py
from flask import Flask
app = Flask(__name__)
Then in a separate file, in the same directory, run.py
然后在一个单独的文件中,在同一个目录中, run.py
from app import app
app.run(
debug = True
)
When I try to run run.py, I get the error
当我尝试运行时run.py,出现错误
Traceback (most recent call last):
File "run.py", line 1, in <module>
from app import app
ImportError: No module named app
采纳答案by Elisha
__init__.pyis imported using a directory. if you want to import it as appyou should put __init__.pyfile in directory named app
__init__.py使用目录导入。如果你想导入它,app你应该把__init__.py文件放在名为的目录中app
a better option is just to rename __init__.pyto app.py
更好的选择是重命名__init__.py为app.py
回答by Takeshi Patterson
Your __init__.pyfile needs to go in the folder named app, not the same directory as the run.py file.
您的__init__.py文件需要放在名为 app 的文件夹中,而不是与 run.py 文件相同的目录中。
from app import appis looking in the app folder, so the __init__.pyfile needs to sit in there.
from app import app正在查找 app 文件夹,因此__init__.py文件需要放在那里。
回答by Nuhman
This is probably an error in flask application's folder structure.
Anyone looking for a simple beginner-friendly structure for the flask project may find this helpful:
这可能是 Flask 应用程序文件夹结构中的错误。
任何人寻找一个烧瓶项目一个简单的初学者友好的结构可能会有所帮助:
|__movies
|__run.py
|__app
├── templates
│ └── index.html
│ └── signup.html
└── __init__.py
└── routes.py
Here 'movies' is the name given for the main application. It contains 'run.py' and a folder called 'app'. 'app' folder contains all necessary flask files such as 'templates' folder, '__init __.py', and 'routes.py'.
这里的“电影”是主应用程序的名称。它包含“ run.py”和一个名为“ app”的文件夹。“应用程序”文件夹包含所有必要的文件烧瓶诸如“模板”文件夹,“ __init __.py”和“ routes.py”。
Contents of:
内容:
run.py:
运行.py:
from app import app
__init__.py:
__init__.py:
from flask import Flask
app = Flask(__name__)
from app import routes
app.run(debug=True)
routes.py:
路线.py:
from app import app
@app.route('/')
@app.route('/index')
def index():
return "Hello, World!"
回答by csc_n00b
Ensure to set your PYTHONPATH to the src/ directory as well. Example
export PYTHONPATH="$PYTHONPATH:/path/to/your/src"
确保将您的 PYTHONPATH 也设置为 src/ 目录。例子
export PYTHONPATH="$PYTHONPATH:/path/to/your/src"

