Python:无法导入模块

时间:2019-05-17 04:03:20

标签: python flask

我正在从https://blog.miguelgrinberg.com/学习烧瓶

我有名为microblog.py的应用程序微博

from app import app

,我有一个名为app的目录,它包含带有以下代码的__init__.py

from flask import Flask
from config import Config

app = Flask( __name__ )
app.config.from_object(Config)
from app import routes

但是当我运行flask run时,我得到了错误

ImportError: No module named 'app'

我了解,如果我想将目录表示为包,那么我必须在目录内包含__init__.py,而对于app目录则是如此。

目录结构

.
├── __init__.py
├── app
│   ├── __init__.py
│   ├── forms.py
│   ├── routes.py
│   └── templates
│       ├── base.html
│       ├── index.html
│       └── login.html
├── config.py
└── microblog.py

完整的堆栈跟踪


flask run                                       
 * Serving Flask app "microblog.py"
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
Usage: flask run [OPTIONS]

Error: While importing "microblog.microblog", an ImportError was raised:

Traceback (most recent call last):
  File "~/anaconda3/envs/flask_python3.5.2/lib/python3.5/site-packages/flask/cli.py", line 235, in locate_app
    __import__(module_name)
  File "~/learning/migual_flask/microblog/microblog.py", line 1, in <module>
    from app import app
ImportError: No module named 'app'

这段代码一直工作到最近,突然开始引起麻烦。我无法找到问题所在。

任何帮助,我们将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:3)

好的,从您在层次结构中发布的内容来看,很明显它应该可以工作,但是我怀疑您是从错误的目录中导入的。

给出目录:

.
├── __init__.py
├── app
│   ├── __init__.py
│   ├── forms.py
│   ├── routes.py
│   └── templates
│       ├── base.html
│       ├── index.html
│       └── login.html
├── config.py
└── microblog.py

假设您从根目录(顶部的“。”)导入它们:

$ls                                                                                                                                                        
__init__.py  app          config.py    microblog.py

$ls app
__init__.py  forms.py     routes.py

# which works
>>> import config
>>> import microblog
>>> import app

# and
>>> from app import routes
>>> from app import forms

我注意到您的app = Flask()中有app/__init__.py,这是一个非常糟糕的做法,应尽可能避免(这使您认为这很好,这是我想不到的吗? ),但对我有用:

>>> import app
>>> from app import app

# the first app is module
# the second is app = Flask()
# but the second one will overwrite the first one's name
# which is another terrible practice

您可以检查模块:

>>> import app
>>> help(app) # app = Flask() is there