Click here to Skip to main content
15,848,407 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Im currently trying to get a register and login working with Flask using SQLAlchemy for the database side of things. When I run the app.py file I get the error:

ImportError: cannot import name db in Flask

I'm fairly new to python flask and can't seem to figure this out. Thank you in advance for the suggestions.

What I have tried:

app.py File
Python
from flask import Flask, request, render_template, redirect, url_for
from forms import SignupForm

from models import db
def init_db():
    db.init_app(app)
    db.app = app
    db.create_all()

from flask_login import LoginManager, login_user, login_required, logout_user 
login_manager = LoginManager()
login_manager.init_app(app)

app = Flask(__name__)
app.secret_key = 'secretkeyhereplease'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////database/database.sqlite'

@app.route('/')
def index():
    return "Welcome to Flask"

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    form = SignupForm()

    if request.method == 'GET':
        return render_template('signup.html', form = form)
    elif request.method == 'POST':
        if form.validate_on_submit():
            if user.query.filter_by(email=form.email.data).first():
                return "Email address already exists"
            else:
                newuser = User(form.email.data, form.password.data)
                db.session.add(newuser)
                db.session.commit()

                login_user(newuser)

                return "Will create user here"
        else: 
            return "Form didn't validate"

@login_manager.user_loader
def load_user(email):
    return User.query.filter_by(email = email).first()

@app.route('/protected')
@login_required
def protected():
    return "protected area"

app.route('/login', methods=['GET', 'POST'])
def login():
    form = SignupForm()

    if request.method == 'GET':
        return render_template('login.html', form=form)
    elif request.method == 'POST':
        if form.validate_on_submit():
            user=User.query.filter_by(email=form.email.data).first()
            if user:
                if usee.password == form.password.data:
                    login_user(user)
                    return "User logged in"
                else:
                    return "Wrong password"
            else:
                return "User doesn't exist"
    else:
            return "Form not validated"     

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


models.py File
from app import app
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)

class User(db.Model):
    email = db.Column(db.String(80), primary_key=True, unique=True)
    password = db.Column(db.String(80))

    def __init__(self, email, password):
        self.email = email
        self.password = password

    def __repr__(self):
        return '<User %r>' % self.email

    def is_authenticated(self):
        return True
    def is_active(self):
        return True
    def is_anonymous(self):
        return False
    def get_id(self):
        return str(self.email)
Posted
Updated 14-Sep-18 5:56am

1 solution

You should import and initialize db from app.py, then import db to models file

Python
from flask_sqlalchemy import SQLAlchemy

Then initialize it
Python
db = SQLAlchemy(app)


In models.py
Python
from app import db
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900