Importing app when using Alembic raises ImportError
Asked Answered
A

4

8

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?

Armoured answered 20/11, 2015 at 7:47 Comment(1)
Try change your package(app) name?Haughty
S
14

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
Sanctuary answered 20/11, 2015 at 8:4 Comment(1)
I am trying to study how to use alembic in flask, so I run the command: alembic upgrade headArmoured
I
7

alembic just tries to load your env.py source code. It's not in your package, so it can't access your app module.

Use solution 2 @tomasz-jakub-rup suggested, you can execute like

$ PYTHONPATH=. alembic upgrade head

and you should get your result.

Ictus answered 20/11, 2015 at 8:20 Comment(0)
F
5

Create file .env and insert PYTHONPATH=.

Fairhaired answered 2/12, 2019 at 18:14 Comment(0)
P
1

Add prepend_sys_path = . into alembic.ini file like this:

[alembic]
# path to migration scripts
script_location = alembic
prepend_sys_path = .
Parole answered 22/9, 2023 at 12:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.