0

I'm building a web Flask- SQLAlchemy application, following step-by step from a Udemy course but as soon as I type...

 from app import db

... in the terminal, I receive a "cannot import name 'db' from app" error. As you can see from the code below, I have already used 'pip' to install Flask and SQLAlchemy.

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

app= Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:postgres123@localhost/height_collector'

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)

@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(email, height)
        return render_template("index.html")

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

Could the error be further down? Still a noob so not too sure what the instructor is doing here.

Werner
  • 1
  • 4
  • Why do you type `from app import db` from your terminal ? – thomask Feb 28 '20 at 14:00
  • What does the tutorial ask you to do exactly? – Saiprasad Balasubramanian Feb 28 '20 at 14:02
  • @thomask Apparently it is to create a new instance of the Class 'Data'. (I've edited the post to include the code for the whole app.py file). He then imports the db object from the script (apparently also where the last 3 lines of code comes into handy. He first types python and then >>>from app import db That's when I get the error message – Werner Feb 28 '20 at 14:15
  • @SaiprasadBalasubramanian It is a web app that asks the user for his/her email address and height (in cm). After submitting the information, the user receives an email message with his/her height and the number average height of user who submitted their height as well. There's a separate _html_ and _css_ file for the content – Werner Feb 28 '20 at 14:18

2 Answers2

0

The issue here is you are importing db instance before it is created. There is a similar question answered already. flask - blueprint - sqlalchemy - cannot import name 'db' into moles file

Ravi_Kumar
  • 18
  • 4
0

The filename where you save the code above should be called app.py.

argyris
  • 23
  • 7