我是 Flask 和后端的初学者,我现在真的不了解任何 SQL...
我一直在 Youtube 上学习有关创建 Flask 应用程序的教程,当我尝试添加广告管理员用户时遇到错误。我尝试重新创建一个基本应用程序,并尝试通过仅创建管理模型并尝试将内容放入其中来缩小问题范围,它向我显示了相同的错误。
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class Admin(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), nullable=False)
password = db.Column(db.String(20), nullable=False)
def __repr__(self):
return f"Admin('{self.username}', '{self.password}')"
@app.route('/')
def hello_world():
admin = Admin(username='Justas', password='test')
db.session.add(admin)
db.session.commit() # Error at here
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
当我尝试运行它时,这会显示在终端中
python app.py
Traceback (most recent call last):
File "C:\Users\Sarunas\Desktop\test APP\my_app\env\Lib\site-packages\sqlalchemy\engine\base.py", line 1283, in _execute_context
self.dialect.do_execute(
File "C:\Users\Sarunas\Desktop\test APP\my_app\env\Lib\site-packages\sqlalchemy\engine\default.py", line 590, in do_execute
cursor.execute(statement, parameters)
sqlite3.IntegrityError: UNIQUE constraint failed: admin.username
The above exception was the direct cause of the following exception:
...
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: admin.username
[SQL: INSERT INTO admin (username, password) VALUES (?, ?)]
[parameters: ('Justas', 'test')]
(Background on this error at: http://sqlalche.me/e/gkpj)
错误消息表明您正在尝试创建已存在的管理员。您可以通过在创建新管理员之前添加检查来避免这种情况;
if db.session.query(Admin).filter_by(username='Justas').count() < 1:
admin = Admin(username='Justas', password='test')
db.session.add(admin)
db.session.commit()
return 'Hello, World!'
请用上面的代码测试一下。