简体   繁体   English

使用 Alembic 时导入应用程序会引发 ImportError

[英]Importing app when using Alembic raises ImportError

I am trying to study how to use alembic in flask, I want to import a method in flask app:我正在尝试研究如何在烧瓶中使用 alembic,我想在烧瓶应用程序中导入一个方法:

tree .
.
├── README.md
├── alembic
│   ├── README
│   ├── env.py
│   ├── env.pyc
│   ├── script.py.mako
│   └── versions
│       ├── 8f167daabe6_create_account_table.py
│       └── 8f167daabe6_create_account_table.pyc
├── alembic.ini
├── app
│   ├── __init__.py
│   ├── main
│   │   ├── __init__.py
│   │   ├── errors.py
│   │   ├── forms.py
│   │   └── views.py
│   ├── models.py
│   └── templates
│       ├── 404.html
│       ├── 500.html
│       ├── base.html
│       ├── index.html
│       └── user.html
├── config.py
├── data.sqlite
├── manage.py
└── requirements.txt

in app/__init__.py :app/__init__.py 中

def create_app(config_name):
  app = Flask(__name__)

I want to import create_app in env.py :我想在env.py导入create_app

from app import create_app

but the error shows as below when I run the command alembic upgrade head :但是当我运行命令alembic upgrade head时,错误显示如下:

  File "alembic/env.py", line 5, in <module>
    from app import create_app
ImportError: No module named app

Any idea for this?对此有什么想法吗?

alembic just tries to load your env.py source code. alembic只是尝试加载你的env.py源代码。 It's not in your package, so it can't access your app module.它不在您的包中,因此无法访问您的app模块。

Use solution 2 @tomasz-jakub-rup suggested, you can execute like使用建议的解决方案 2 @tomasz-jakub-rup,您可以像这样执行

$ PYTHONPATH=. alembic upgrade head

and you should get your result.你应该得到你的结果。

I guess you are trying to run我猜你想跑

python env.py

In this case, your app directory is not in PYTHONPATH .在这种情况下,您的应用程序目录不在PYTHONPATH

solution 1解决方案1

Run the app from parent dir:从父目录运行应用程序:

python alembic/env.py

solution 2解决方案2

Set the PYTHONPATH before running the app在运行应用程序之前设置PYTHONPATH

PYTHONPATH=/path/to/parent/dir python env.py

edit编辑

I read about alembic .我读过关于alembic As @mrorno said, just set the PYTHONPATH before running alembic:正如@mrorno 所说,只需在运行 alembic 之前设置PYTHONPATH

PYTHONPATH=. alembic upgrade head

创建文件.env并插入PYTHONPATH=.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM