3

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?

Ismail Badawi
  • 36,054
  • 7
  • 85
  • 97
theprole
  • 2,274
  • 23
  • 25
  • You may want to look at http://stackoverflow.com/questions/9692962/flask-sqlalchemy-import-context-issue for some discussion on alternate ways to do things :-) – Sean Vieira Jul 28 '14 at 13:58

1 Answers1

3

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343