当我使用db.commit.session()
时,我的flask应用程序抛出错误。我看不出我的代码有什么问题。下面是终端中的代码和错误:
>>> user_1 = User(username='Corey', email='C@demo.com', password='password')
>>> db.session.add(user_1)
>>> user_2 = User(username='JohnDoe', email='jd@demo.com', password='password')
>>> db.session.add(user_2)
>>> db.create_all()
>>> db.session.commit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 2, in commit
File "C:Usershpminiconda3libsite-packagessqlalchemyormsession.py", line 1428, in commit
self._transaction.commit(_to_root=self.future)
File "C:Usershpminiconda3libsite-packagessqlalchemyormsession.py", line 827, in commit
self._assert_active(prepared_ok=True)
File "C:Usershpminiconda3libsite-packagessqlalchemyormsession.py", line 608, in _assert_active
code="7s2a",
sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlite3.IntegrityError) UNIQUE constraint failed: user.image_file
[SQL: INSERT INTO user (username, email, image_file, password) VALUES (?, ?, ?, ?)]
[parameters: ('JohnDoe', 'jd@demo.com', 'default.jpg', 'password')]
(Background on this error at: https://sqlalche.me/e/14/gkpj) (Background on this error at: https://sqlalche.me/e/14/7s2a)
老实说,我不知道这是我的终端代码还是我的主代码。
这是我的应用程序的代码:
from datetime import datetime
from flask import Flask, render_template, url_for, flash, redirect
from flask_sqlalchemy import SQLAlchemy
from forms import RegistrationForm, LoginForm
app = Flask(__name__)
app.config['SECRET_KEY'] = 'cac78a5498388aa4a95fb2be0f0a6499'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(20), unique=True, default='default.jpg')
password = db.Column(db.String(60), nullable=False)
posts = db.relationship('Post', backref="author", lazy=True)
def __repr__(self):
return f"User('{self.username}','{self.email}','{self.image_file}')"
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return f"Post('{self.title}','{self.date_posted}')"
问题是,当您指定unique=True
时,您将用户模型的列image_file
定义为'唯一'。当您创建一个新用户(不指定image_file)时,这会抛出一个错误,因为默认的image_file
总是'default.jpg'。基本上,您只需要删除image_file
列中的unique=True
属性,因为新用户(默认情况下)将具有相同的图像文件。