Flask_WTF、SQLAlchemy 和 SQLite 3 登录时没有此类表错误

问题描述 投票:0回答:1

我是一名学生,正在学习如何使用 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 表也存在类似的问题,但我认为解决这个问题也能让我深入了解这些问题。

这是我的相关代码(为简洁起见,省略了不相关的代码):

my 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.\
    \nFilled with filler values.')



#Commit the changes and close 

connect.commit() 

我的表格.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!')

我的模型.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

路线.py。该错误似乎来自“user.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)

最后是文件夹层次结构:

项目: 烧瓶宠物

--- 实例(文件夹)

------site_database.db(空。我不知道它为什么在这里。它是否可能表明某些东西?)

---静态(文件夹)

------(图像文件夹和 css/js)

---模板(文件夹

------(html。我认为没有必要包含它,但如果需要的话我可以稍后在评论中添加它)

---init.py

---app.py

---forms.py

---函数.py

---模型.py

---routes.py

实例(文件夹)(空)

site_database.db(上面写有 app.py 中的表和值)

学分.txt

需求.txt

我尝试了很多事情,比如弄乱 URI 地址、修复表、了解有关 sqlalchemy 和 sql 的更多信息,以及向我的小组项目合作伙伴寻求帮助。我已经为此苦苦思索了 3-4 个小时,但我不明白我做错了什么(尽管我对 SQL 和 Flask 很陌生,所以我要让自己放松一点) .

任何帮助将不胜感激!

python sqlite flask flask-sqlalchemy crud
1个回答
0
投票

创建表和添加用户的最简单方法是在您的

__init__.py
文件中。
为此,必须导入模型并在应用程序上下文中创建表。为此,您可以使用命令
create_all()
。然后,您可以创建用户的实例,将其添加到会话中并使用
commit()
将会话提交到数据库。数据库应创建在 instance 文件夹中。

# ...

from models import * 
from routes import *

with app.app_context():
    db.create_all()
    admin = User(
        username='admin', 
        password='password', 
    )
    db.session.add(admin)
    db.session.commit()

您还可以使用 flask shellFlask-Migrate 扩展来创建表并添加数据。

© www.soinside.com 2019 - 2024. All rights reserved.