NameError: name 'db' is not defined

JMT picture JMT · Jun 24, 2017 · Viewed 7.4k times · Source

I am building a web app with Flask and SQLAlchemy. I can't seem to find out the reason for this error NameError: name'db' is not defined Would really appreciate your help.

(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

Here's app.py, which I have defined db properly according to the documentation

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()

And manage.py

#!/usr/bin/env python

from flask_script import Manager
from app import app, db

manager = Manager(app)


@manager.shell
def make_shell_context():
    """ Creates a python REPL with several default imports
        in the context of the app
    """

    return dict(app=app, db=db)


if __name__ == "__main__":
    manager.run()

Answer

BoarGules picture BoarGules · Jun 24, 2017

Your code is doing from app import User but at line 5 you are expecting it to know about db, which is in app but which you have not imported.

import app
u = app.User()
u.username = 'testusr'
u.password = 'testpwd'
app.db.session.add(u)