Import issues with flash app
I had the following structure in my flash application:
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 the model Trackorder
into a file tasks.py
, but I 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
both 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 solve this problem?
source to share
Here is a solution that might work for you.
Create a file named core.py
(or whatever you want to call 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)
As models.py
you can use this importfrom core import db
This is based on an example here: https://pythonhosted.org/Flask-SQLAlchemy/api.html
source to share
Without complete code with all the imports, it's hard to tell, but you most likely have circular imports. You are importing module B into module A and module B into module A. This has a side effect: while you are importing A into B (the import that closes the loop), there is nothing below the import of B into A. 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: Change the import order or use the operator import
locally, for example:
def function1():
from a import var1
print(var1)
source to share