Search code examples
pythonpython-2.7flasksqlalchemyflask-restful

python module import conundrum (module from submodule)


I have the following project structure:

./app/__init__.py
./app/main/__init__.py
./app/main/views.py
./app/models.py
./app/resources/__init__.py
./app/resources/changesAPI.py
./config.py
./manage.py

The app/models.py file has the following line:

from app import db

db is defined in app/__init__.py

db = SQLAlchemy()

I'm importing classes from models.py from app/resources/__init__.py:

from app.models import User, Task, TaskChange, Revision

However, it fails when model tries to import db:

Traceback (most recent call last):
  File "manage.py", line 5, in <module>
    from app import create_app, db, api
  File "/Users/nahuel/proj/ptcp/app/__init__.py", line 16, in <module>
    from app.resources.changesAPI import ChangesAPI
  File "/Users/nahuel/proj/ptcp/app/resources/__init__.py", line 5, in <module>
    from app.models import User, Task, TaskChange, Revision
  File "/Users/nahuel/proj/ptcp/app/models.py", line 1, in <module>
    from app import db
ImportError: cannot import name db

What am I doing wrong?


Solution

  • You have a circular import.

    You are importing create_app, db and api from manage.py, which triggers an import of the app.resources.changesAPI module, which in turn then triggers import of the __init__.py package in app/resources which then tries to import your models, which fails because db was not yet defined in app/__init__.py.

    You need to move importing ChangesAPI to after the line that defines db in your app/__init__.py file. Any name defined in app/__init__.py before the from app.resources.changesAPI import ChangesAPI is available to your sub-packages, names after are not.