You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask_WTF+SQLAlchemy+SQLite3登录时出现No Such Table Error求助

问题:Flask+SQLite3登录时提示"no such table: user"错误

我是一名正在学习使用Flask和SQLite3开发Web应用的学生,这是我首次提问,若格式或礼仪有问题请见谅。当我尝试登录网站时,出现如下错误:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user   
[SQL: SELECT user.id AS user_id, user.username AS user_username, user.image_file AS user_image_file, user.password AS user_password
FROM user
WHERE user.username = ?
 LIMIT ? OFFSET ?]
[parameters: ('admin', 1, 0)]

注册及使用数据库中其他SQL表时也存在类似问题,我认为解决此问题后就能理清其他问题的思路。

相关代码

init.py(密钥已隐藏)

#<-------- Run this file to launch the site -------->#

#This initializes the base variables that are used in the project

from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy

 
#Start Flask 
app = Flask(__name__)

#Configure Secret Key for Flask 
app.config['SECRET_KEY'] = "XXXX"

#Set SQL to database 
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site_database.db'

#Create a Database variable using SQL ALchemy
db = SQLAlchemy(app)

#Log in Manager instance for user_loader and interface 
# with User Class in models.py
login = LoginManager(app)


#Routes stores the python logic that controls the websites, 
#Models stores some data structure stuff 
from routes import *
from models import * 



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

app.py(用于创建数据库并填充测试数据)

import sqlite3
from __init__ import db


#Create SQL Tables-- 1 for user names and passwords
 
    
connect = sqlite3.connect('site_database.db')
cursor = connect.cursor()
print('Database Opened Successfully.')

# Try Block to attempt to open DB, but bounces out if DB already created 
try:
    print("Attempting to fill database tables...")
    cursor.execute("CREATE TABLE user(id INTEGER NOT NULL , username VARCHAR(20), image_file VARCHAR(20), password VARCHAR(20), UNIQUE (username), PRIMARY KEY (id))")
    print("Database Created")
except:
    print('Database Already Created.')

#Dummy values so we have something in the DB to start 
print('Attempting to fill with values...')
cursor.execute("INSERT OR REPLACE INTO user(id, username, image_file, password) VALUES('0001', 'admin', 'default.jpg', 'password')")

print('Filled with user values.\
    \
Filled with filler values.')



#Commit the changes and close 

connect.commit() 

forms.py

from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, DateField, PasswordField, IntegerField, BooleanField, SubmitField, TextAreaField, SelectField
from wtforms.validators import DataRequired, Length, EqualTo, ValidationError
from models import User 
from flask_login import current_user, AnonymousUserMixin

#Changes Parameters for Guest Users 
class Anonymous(AnonymousUserMixin):
  def __init__(self):
    self.username = 'Guest'


#Basic login information (includes remember me field)
class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(min=2, max =20)])
    password = PasswordField('Password', validators=[DataRequired()])
    remember = BooleanField('Remember Me')
    submit = SubmitField('Sign In!')

models.py

from __init__ import db, login 
from flask_login import UserMixin 
from sqlalchemy import *
from flask_sqlalchemy import *

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key= True, unique = True)
    username = db.Column(db.String(64), index = True, unique = True, nullable = False)
    image_file = db.Column(db.String(20), nullable = False, default = 'default.jpg')
    password = db.Column(db.String(20), nullable = False)
    try:    
        pets = db.relationship('Pet', backref = 'author_post', lazy = True)
    except:
        pass

routes.py(错误来自User.query.filter_by(username=form_username).first()语句)

from flask import render_template, url_for, redirect, flash, session, request, abort
from flask_login import login_user, logout_user, current_user, login_required, LoginManager
from __init__ import *
from functions import * 
from models import * 
from forms import *
import uuid 
# Log in using login-manager authentication 
@app.route('/login', methods=['GET', 'POST'])
def login():

    #Pushes user back to home if logged in 
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()

    #Get form data  
    form_username = form.username.data
    form_password = form.password.data

    #Verify if the user input matches user and pass on file, 
    # pops a warning if not, logs in (with a cookie making it permanent-ish) if succeeds  
    if form.validate_on_submit(): 
        user = User.query.filter_by(username=form_username).first()
        password = user.password 
        if user is None or password != form_password:
            flash("Login Unsuccessful. Please verify your username and password.", "danger")
            return redirect(url_for('login'))
        login_user(user)
        session.permanent = True 
        return redirect(url_for('login'))
    return render_template('login.html', title = 'Login', form = form)

目录结构

项目:Flaskpet
├── instance(文件夹)
│   └── site_database.db(为空)
├── static(文件夹)
│   └── (图片文件夹及css/js文件)
├── templates(文件夹)
│   └── (html文件)
├── __init__.py
├── app.py
├── forms.py
├── functions.py
├── models.py
├── routes.py
├── instance(文件夹)(为空)
├── site_database.db(包含app.py写入的表和数据)
├── credits.txt
└── requirements.txt

已尝试的解决方法

  • 修改数据库URI地址
  • 修复表结构
  • 学习SQLAlchemy和SQL相关知识
  • 询问项目组伙伴

折腾3-4小时仍未解决,本人是SQL和Flask新手,恳请帮助!

内容的提问来源于stack exchange,提问作者Seb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 07:40:55