每当我尝试在python控制台中导入init db时:
>>from app.database import init_db
>>init_db()
init db
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "app\database.py", line 18, in init_db
import models
ImportError: No module named models
这是我的app.database功能的内容:
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from config import SQLALCHEMY_DATABASE_URI
engine = create_engine(SQLALCHEMY_DATABASE_URI, convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def init_db():
# import all modules here that might define models so that
# they will be registered properly on the metadata. Otherwise
# you will have to import them first before calling init_db()
print "init db"
import models
Base.metadata.create_all(bind=engine)
为什么会这样?
更新:这是我项目的结构。
app/
filebase/
init.py
models.py
users/
init.py
models.py
projects/
init.py
models.py
init.py
database.py (this is where the init_db was defined
至于为什么看起来像这样的结构,原因是使项目以其形式模块化。
答案 0 :(得分:0)
您需要models.py
(或models
包的)父目录位于sys.path
。您可以将它放在控制台会话中,或者在shell中将其添加到环境变量PYTHON_PATH
中,以便在进入控制台会话时设置它。