这是我第一次玩 SQLAlchemy,我正试图将一个项目插入表中并让烧瓶打印出该项目。但是,当我没有捕获异常时,我会不断收到这样的完整性错误:
sqlalchemy.exc.IntegrityError: (IntegrityError) column email is not unique u'INSERT INTO user (username, email) VALUES (?, ?)' ('test', 'test@gmail.com')
我有以下代码:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return "<User %r>" % self.username
@app.route("/")
def index():
return User.query.all() # I don't think this will work
if __name__ == "__main__":
db.create_all()
try:
x = User("test", "test@gmail.com")
db.session.add(x)
db.session.commit()
print "worked"
except IntegrityError:
print "Not Working"
app.run(debug=True)
有人介意伸出援手吗?我对 IntegrityError 进行了一些研究,但大多数文档都是关于处理错误而不是防止它。