SQLAlchemy NameError: Name 'db' is not defined (?)

Question:

I am working on a Udemy course using flask to record heights. I am at the point where we are using PostgreSQL, and I have it installed, and I have his code copied exactly:

from flask import Flask, render_template, request
from flask.ext.sqlalchemy import SQLAlchemy

app=Flask(__name__) 

app.config(['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:password
@localhost/height_collector')

db=SQLAlchemy(app)

class Data(db.Model):
__tablename__='data'
id=db.Column(db.Integer, primary_key=True)
email_=db.Column(db.String(120), unique=True)
height_=db.Column(db.Integer)

def __init__(self, email_, height_):
    self.email_=email_
    self.height_=height_
@app.route("/")
def index():
   return render_template("index.html")

@app.route("/success", methods=["post"])
 def success():
if request.method=='POST':
    email=request.form['email_name']
    height=request.form['height_name']
    print(height,email)
return render_template("success.html")

if __name__=='__main__':
   app.debug=True
app.run()

Problem comes into play, when he says to run python in a virtual env, and then enter :db.create_all() to create a database in PostgreSQL and I get this error :
File <‘stdin’>, line 1 in
NameError: Name ‘db’ is not defined

Not sure how to proceed, any input would be appreciated.

Asked By: user8341748

||

Answers:

I think you probably need to run some of the other code first so that you define db and your table schema. Then you can run db.create_all().

from flask import Flask, render_template, request
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__) 

app.config(['SQLALCHEMY_DATABASE_URI'] = 
           'postgresql://postgres:password@localhost/height_collector')

db = SQLAlchemy(app)

class Data(db.Model):
    __tablename__ = 'data'
    id = db.Column(db.Integer, primary_key=True)
    email_ = db.Column(db.String(120), unique=True)
    height_ = db.Column(db.Integer)

    def __init__(self, email_, height_):
        self.email_ = email_
        self.height_ = height_

db.create_all()
Answered By: Andrew Guy

you can make a db.py where you can store the code db = SQLAlchemy(). Then import in in app.py. now you can able to call db. or just remove APP in db=SQLAlchemy(app)

Answered By: Jay

Start python shell by running the command python. Then import db to define it:

from main import db
db.drop_all()
db.create_all()
Answered By: user9202135

You need to set the FLASK env variable.

create a .flaskenv file in the top directory of your project
Add this to your .flaskenv file:

export FLASK_APP=myappfile.py

Install dotenv to your environment

pip install python-dotenv

Now if you run the app it should pick up your env variable.

Answered By: Ger Mc

Type the Following and it will work:

cd flask-app
venvscriptsactivate
python3
from app import db
db.create_all()
Answered By: Zani Kastrati

I just faced this error and it is because I didn’t import db before calling the db function. If you’re running in terminal, ‘from yourappname import db’ and any other functions you are running.

//IN TERMINAL
from yourappname import db
Answered By: Darren Odi
#write at top of your model
from . import db
Answered By: zesty