Flask-Web-App-Tutorial icon indicating copy to clipboard operation
Flask-Web-App-Tutorial copied to clipboard

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user

Open Chris-D-Wayne opened this issue 3 years ago • 3 comments

Hi everyone,

I followed Tims (amazing) video on YT - I'm now trying to use the concepts from the video to rebuild this project into a small web shop, I've tried comparing my code to the current code repo that tim provided with meld but whenever I'm trying to sign up a new user I'm getting the following Error:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user [SQL: SELECT user.id AS user_id, user.email AS user_email, user.password AS user_password, user."firstName" AS "user_firstName", user."lastName" AS "user_lastName" FROM user WHERE user.email = ? LIMIT ? OFFSET ?] [parameters: ('test@testy', 1, 0)] (Background on this error at: https://sqlalche.me/e/14/e3q8)

I haven't found a similar issue here, so sorry if this has already been posted somewhere, the error states no such table: user, but I'm pretty sure I'm initializing the db correctly. Any help would be greatly appreciated! Thanks in advance, see parts of my code down below.

main.py:

from website import create_app

app = create_app()

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

init.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
#from flask_login import LoginManager

db = SQLAlchemy()
DB_NAME = "database.db"


def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'BatShop123'
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
    db.init_app(app)

    from .views import views
    from .auth import auth

    app.register_blueprint(views, url_prefix='/')
    app.register_blueprint(auth, url_prefix='/')

    from .models import User

    create_database(app)

    #login_manager = LoginManager()
    #login_manager.login_view = 'auth.login'
    #login_manager.init_app(app)

    #@login_manager.user_loader
    #def load_user(id):
        #return User.query.get(int(id))

    return app


def create_database(app):
    if not path.exists('website/' + DB_NAME):
        db.create_all(app=app)
        print('Created Database!')

views.py

from flask import Blueprint, render_template, request, flash, jsonify
from flask_login import login_required, current_user
from . import db
import json

views = Blueprint('views', __name__)


@views.route('/', methods=['GET', 'POST'])
def home():
    return render_template("home.html")

auth.py

from flask import Blueprint, render_template, request, flash, redirect, url_for
from .models import User
from werkzeug.security import generate_password_hash, check_password_hash
from . import db
from flask_login import login_user, login_required, logout_user, current_user


auth = Blueprint('auth', __name__)


@auth.route('/login', methods=['GET', 'POST'])
def login():
    #TBA
    return render_template("login.html")

@auth.route('/sign_up', methods=['GET', 'POST'])
def sign_up():
    if request.method == 'POST':
        email = request.form.get('email')
        first_name = request.form.get('firstName')
        last_name = request.form.get('lastName')
        password1 = request.form.get('password1')
        password2 = request.form.get('password2')

        user = User.query.filter_by(email=email).first()
        if user:
            flash('Email already exists.', category='error')
        elif len(email) < 4:
            flash('Email must be greater than 3 characters.', category='error')
        elif len(first_name) < 2:
            flash('First name must be greater than 1 character.', category='error')
        elif password1 != password2:
            flash('Passwords don\'t match.', category='error')
        elif len(password1) < 7:
            flash('Password must be at least 7 characters.', category='error')
        else:
            new_user = User(email=email, firstName=first_name, lastName=last_name, password=generate_password_hash(
                password1, method='sha256'))
            db.session.add(new_user)
            db.session.commit()
            login_user(new_user, remember=True)
            flash('Account created!', category='success')
            return redirect(url_for('views.home'))

    return render_template("sign_up.html")

models.py

from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func



class Item(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    productName = db.Column(db.String(10000))
    quantity = db.Column(db.Integer)
    userId = db.Column(db.Integer, db.ForeignKey('user.id'))    

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    firstName = db.Column(db.String(150))
    lastName = db.Column(db.String(150))
    inventory = db.relationship('Item')

Chris-D-Wayne avatar Jul 28 '22 12:07 Chris-D-Wayne

Hello @Chris-D-Wayne. I had the same error and spent a lot of time looking for a solution. What worked for me was to delete the database.DB file I had and rerun the app making it create a new database file. I hope that fixes your situation

MKoushikYadav avatar Aug 04 '22 04:08 MKoushikYadav

i have the same issue, did you solve it somehow?

MarcoAntolini avatar Jan 24 '23 01:01 MarcoAntolini

i have the same issue, did you solve it somehow?

Hi, I did it like already mentioned above, I deleted the whole database file and reinitialised it, that solved the problem for me.

Chris-D-Wayne avatar Jan 24 '23 06:01 Chris-D-Wayne