我正在使用Flask和SQLAlchemy构建一个Web应用程序。
我似乎无法找出导致此错误的原因for
真的很感谢你的帮助。
NameError: name'db' is not defined
这是(wfdb-venv) J-2:wfdb j$ python3 manage.py shell
Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.1.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from app import User
In [2]: u = User()
In [3]: u.username = 'testusr'
In [4]: u.password = 'testpwd'
In [5]: db.session.add(u)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~/Documents/Learning/Python/Flask/wfdb/wfdb-venv/lib/python3.6/site-packages/flask_script/commands.py in <module>()
----> 1 db.session.add(u)
NameError: name 'db' is not defined
,我根据documentation正确定义了数据库
app.py
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///database.db"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer(), primary_key=True)
username = db.Column(db.String(), unique=True)
password = db.Column(db.String())
def __repr__(self):
return '<User {}>'.format(self.username)
@app.route("/")
def home():
return render_template("index.html")
if __name__ == "__main__":
app.run()
manage.py
答案 0 :(得分:0)
您的代码正在执行from app import User
,但在第5行,您希望它了解db
,app
中的 ,但您拥有不导入。
import app
u = app.User()
u.username = 'testusr'
u.password = 'testpwd'
app.db.session.add(u)