Search code examples
pythonimportflaskalembic

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:

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:

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

I want to import create_app in env.py:

from app import create_app

but the error shows as below when I run the command 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?


Solution

  • I guess you are trying to run

    python env.py
    

    In this case, your app directory is not in PYTHONPATH.

    solution 1

    Run the app from parent dir:

    python alembic/env.py
    

    solution 2

    Set the PYTHONPATH before running the app

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

    edit

    I read about alembic. As @mrorno said, just set the PYTHONPATH before running alembic:

    PYTHONPATH=. alembic upgrade head