nish
nish

Reputation: 7280

Import issues with flask app

I had the following structure in my flask app:

app.py:

app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
db = SQLAlchemy(app)
from models import *

models.py:

from app import db

It worked fine until I wanted to do read/write operations on models in files other than app.py. I tried to import model Trackorder in a file tasks.py but got the following error:

ImportError: cannot import name TrackOrder

So, I changed the structure:

__init__.py:

app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
db = SQLAlchemy(app)

But this makes app and db unavailable in app.py and models.py:

File "app.py", line 21, in <module>
    from models import *
  File "/home/nish/repos/stage/voylla_api/models.py", line 16, in <module>
    class Product(db.Model):
NameError: name 'db' is not defined

##after commenting models.py:
Traceback (most recent call last):
  File "app.py", line 210, in <module>
    @app.route('/')
NameError: name 'app' is not defined

How can I resolve this issue?

Upvotes: 4

Views: 2424

Answers (2)

Gohn67
Gohn67

Reputation: 10648

Here is a solution that could work for you.

Create a file named core.py (or whatever you want to name it):

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

Now in app.py:

from core import db

app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])

# Instead of this line: db = SQLAlchemy(app)
# Use this approach to initialize db
db.init_app(app)

In your models.py you can use this import from core import db

This is based on the example here: https://pythonhosted.org/Flask-SQLAlchemy/api.html

Upvotes: 4

Klaus D.
Klaus D.

Reputation: 14404

Without the full code with all import statement it's hard to say, but you most likely have a cyclic import. You are importing module B in module A and module B in module A. This has the side-effect, that at the time you are importing A into B (the import that closes the cycle) nothing below the import of B is available in A. An example:

a.py:
from b import * # Now b.py is evaluated before the execution contiues.
var1 = 0

b.py:
import a
print(a.var1) # This raises an error since var1=0 was not executed yet.

Solution: Reorder your imports or use the import statement locally, like:

def function1():
    from a import var1
    print(var1)

Upvotes: 0

Related Questions