6
votes

I am learning flask . Using sqlalchemy for orm and alembic for migrations Going through and following: http://alembic.readthedocs.org/en/latest/autogenerate.html

whenever i pass the command " alembic revision --autogenerate -m 'name' " , this error pops up . whatever i do , i configured the config.py file but i think maybe i am configuring the env.py file the wrong way . Or something is wrong because i followed every step of the tutorial.

File "alembic/env.py", line 20, in <module>
from myapp.mymodel import Base
ImportError: No module named app.models




folder directory:
project/
       app/
          models.py
          views.py
          __init__.py
       alembic/
              versions
              env.py
       config.py
3

3 Answers

19
votes

When you run the alembic command, your app package is not in Python's module path. So it can't be imported. The easiest way to solve this is to use an extension such as Flask-Migrate or Flask-Alembic to handle setting up the migration environment for you. Both these extensions require you to use Flask-SQLAlchemy as well.

If you don't want to use an extension, the quick and dirty way is to just force the directory containing your app package to be on the path. In env.py, before importing Base, add

import os, sys
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(__file__), '..')))

A better solution would be to properly set up your project with a setup.py file and install your package in editable mode: pip install -e .. Then your package would be on the path the "right" way, as if it were actually installed.

4
votes

You should use export PYTHONPATH='.'

0
votes

you need to add the absolute path to the root directory where your alembic folder lives. Eg:

If your current folder structure is:

 .
├── app
│   ├── alembic
│   │   ├── env.py
│   │   ├── __pycache__
│   │   ├── README
│   │   ├── script.py.mako
│   │   └── versions
│   ├── alembic.ini
│   ├── constants
│   ├── core
│   ├── enums
│   ├── models
│   ├── repository
│   ├── routes
│   ├── __init__.py
│   ├── main.py

and your app has absolute path of:

/home/username/dev/app

then run the following line to add the path in your ~/.bashrc or ~/.zshrc for local development and update the env variables.

echo "export $PYTHONPATH=$PYTHONPATH:/home/username/dev/app" >> ~/.bashrc
source ~/.bashrc

or

echo "export $PYTHONPATH=$PYTHONPATH:/home/username/dev/app" >> ~/.zshrc
source ~/.zshrc