Flask/Python 应用程序:OperationalError: (sqlite3.OperationalError) 没有这样的表:user

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

app.py

#basic flask skeleton
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from JobApplicationTracker.models import User


#Flask application instance named app - __name__ represents the current module
app = Flask(__name__)

#configure SQLite db URI
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///job-application-tracker.db'

#disable track mods
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

#route for the root url ("/"). root url is visited - func below is executed
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        email = request.form.get('email')
        password = request.form.get('password')

        #new user object
        new_user = User(username=username, email=email, password=password)
        db.session.add(new_user)
        db.session.commit()

        return redirect(url_for('success'))

    return render_template('registration.html')

@app.route('/success')
def success():
    return render_template('success.html')

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

模型.py

#Flask-SQLAlchemy: an extension for integrating SQLAlchemy with Flask for database management.
#werkzeug.security is imported to use functions for password hashing and verification.
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash


#SQLAlchemy instance - represents application's database connection
db = SQLAlchemy()

#user class inherits from db.Model (base class provided by flask)
class User(db.Model):
    __tablename__ = "user"
    #identifier for each user in database
    id = db.Column(db.Integer, primary_key=True) 

    #each username/email in the db must be unique and cannot be empty
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    #stores the hashed version of the user's password
    password_hash = db.Column(db.String(128), nullable=False)

    def __init__(self,username,email,password): #initalize/constructor
        self.username = username
        self.email = email
        #hashes and sets the user's password
        self.set_password(password)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        #verifies a password during l
        return check_password_hash(self.password_hash, password)

需求.txt

aiofiles==22.1.0
aiosqlite==0.18.0
alembic==1.12.0
anyio==3.6.2
appnope==0.1.3
argon2-cffi==21.3.0
argon2-cffi-bindings==21.2.0
arrow==1.2.3
asttokens==2.2.1
attrs==22.2.0
Babel==2.12.1
backcall==0.2.0
beautifulsoup4==4.12.0
bleach==6.0.0
blinker==1.6.2
certifi==2022.12.7
cffi==1.15.1
charset-normalizer==3.1.0
click==8.1.7
comm==0.1.3
debugpy==1.6.6
decorator==5.1.1
defusedxml==0.7.1
executing==1.2.0
fastjsonschema==2.16.3
Flask==2.3.3
Flask-Login==0.6.2
Flask-Migrate==4.0.4
Flask-SQLAlchemy==3.0.5
Flask-WTF==1.1.1
fqdn==1.5.1
idna==3.4
ipykernel==6.22.0
ipython==8.11.0
ipython-genutils==0.2.0
isoduration==20.11.0
itsdangerous==2.1.2
jedi==0.18.2
Jinja2==3.1.2
json5==0.9.11
jsonpointer==2.3
jsonschema==4.17.3
jupyter-events==0.6.3
jupyter-ydoc==0.2.3
jupyter_client==8.1.0
jupyter_core==5.3.0
jupyter_server==2.5.0
jupyter_server_fileid==0.8.0
jupyter_server_terminals==0.4.4
jupyter_server_ydoc==0.8.0
jupyterlab==3.6.2
jupyterlab-pygments==0.2.2
jupyterlab_server==2.21.0
Mako==1.2.4
MarkupSafe==2.1.2
matplotlib-inline==0.1.6
mistune==2.0.5
nbclassic==0.5.3
nbclient==0.7.2
nbconvert==7.2.10
nbformat==5.8.0
nest-asyncio==1.5.6
notebook==6.5.3
notebook_shim==0.2.2
packaging==23.0
pandocfilters==1.5.0
parso==0.8.3
pexpect==4.8.0
pickleshare==0.7.5
platformdirs==3.2.0
prometheus-client==0.16.0
prompt-toolkit==3.0.38
psutil==5.9.4
ptyprocess==0.7.0
pure-eval==0.2.2
pycparser==2.21
Pygments==2.14.0
pyrsistent==0.19.3
python-dateutil==2.8.2
python-json-logger==2.0.7
PyYAML==6.0
pyzmq==25.0.2
requests==2.28.2
rfc3339-validator==0.1.4
rfc3986-validator==0.1.1
Send2Trash==1.8.0
six==1.16.0
sniffio==1.3.0
soupsieve==2.4
SQLAlchemy==2.0.20
stack-data==0.6.2
terminado==0.17.1
tinycss2==1.2.1
tornado==6.2
traitlets==5.9.0
typing_extensions==4.7.1
uri-template==1.2.0
urllib3==1.26.15
wcwidth==0.2.6
webcolors==1.13
webencodings==0.5.1
websocket-client==1.5.1
Werkzeug==2.3.7
WTForms==3.0.1
y-py==0.5.9
ypy-websocket==0.8.2

我还附上了文件结构和我收到的错误的屏幕截图。 File Structure Error message in browser

我正处于使用 Python3 和 Flask 创建应用程序的早期阶段。我的数据库使用 SQLite,在尝试将用户添加到数据库时遇到错误。 “/”路线加载正常,我可以毫无问题地转到

'/register'
路线,但是当我在输入用户名、电子邮件和密码后点击实际注册按钮时,出现错误。我浏览过类似的帖子,但没有帮助。我的许多尝试都集中在使用 db.create_all() (这是我从这里的其他帖子中获得的),但我也看到了相互冲突的资源,这些资源说
db = SQLAlchemy(app)
相当于这样做。此外,我还尝试执行以下 3 个命令:
flask db init
flask db migrate
flask db upgrade
,这两个命令似乎都不起作用。此时我有点不知道该做什么以及如何继续解决此错误。

感谢您的帮助。

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

使用上面的 models.py 文件,但重命名

__init__
方法,请对 app.py 尝试以下操作

#basic flask skeleton
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from JobApplicationTracker.models import User, db  # use the db from your models.py file

#Flask application instance named app - __name__ represents the current module
app = Flask(__name__)

#configure SQLite db URI
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///job-application-tracker.db'

#disable track mods
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(app)  # use init_app instead of the SQLAlchemy contsructor

#route for the root url ("/"). root url is visited - func below is executed
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        email = request.form.get('email')
        password = request.form.get('password')

        #new user object
        new_user = User(username=username, email=email)
        new_user.set_password(password)  # set password after constructor

        db.session.add(new_user)
        db.session.commit()

        return redirect(url_for('success'))

    return render_template('registration.html')

@app.route('/success')
def success():
    return render_template('success.html')

if __name__ == '__main__':
    with app.app_context():  # create the database tables
        db.create_all()
    app.run(debug=True)

至少应该让您的应用程序运行并创建数据库表,现在可以正确处理password_hash保存。

与原始版本相比的更改:

  • 在app.py中
    • 从 models.py 文件导入数据库对象
    • 调用 db.init_app(app) 而不是使用 SQLAlchemy 构造函数创建新数据库
    • 显式调用 new_user 上的 set_password 方法
    • db.create_all()
      块内运行
      with app.app_context()
      • 对于生产,您可能希望将其移至单独的脚本来创建数据库。您不需要每次启动服务器时都运行它。
  • 在 models.py 中
    • 重命名或删除
      __init__
      方法。
© www.soinside.com 2019 - 2024. All rights reserved.