问题
I'm building a web app that uses Flask and SQLAlchemy, but I can't seem to see the reason why this won't import correctly and work.
I'm trying to test my database that I'm building, but I keep getting a NameError
:
File1:
from flask.ext.sqlalchemy import SQLAlchemy
from flask import Flask
from File2 import db, data1, data2, data3
File2:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///DB_File.db' # Uses '///' because '////' puts the file in '/' on server.
db.SQLAlchemy(app)
File2 is followed by some classes that inherit db.Model
, but I don't think I need to include these in here.
To get the error, I'm pulling up a Python interpreter and doing import File1
. This looks like:
>>> import File1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Tux/code/AppName/app/Util/File1.py", line 6, in <module>
from KarmaCourtDB import db, data1, data2, data3
File "/Tux/code/AppName/app/Util/File2.py", line 6, in <module>
db.SQLAlchemy(app)
NameError: name 'db' is not defined
I'd really appreciate it if someone could help me out or point me in the right direction! This code was working before and I could create the database by using db.create_all()
after importing it.
回答1:
db.SQLAlchemy(app)
is not defining db
, and is only attempting to run a SQLAlchemy()
method on db
.
db = SQLAlchemy(app)
however, would define db
.
来源:https://stackoverflow.com/questions/27632513/why-do-i-get-a-nameerror-with-this-import