【发布时间】:2014-06-18 16:37:58
【问题描述】:
我正在尝试解析一些 RSS 提要并使用 flask-sqlalchemy 将 URL 写入数据库。
其中一些提要重叠(即同一篇文章出现在多个提要中或多次出现在同一个提要中),因此我将主键定义为 URL 的(非随机)散列。
我的问题是,当我遍历 URL 并将它们添加到 Session 时,当我尝试将它们提交到数据库时遇到异常。
这是我的代码:
for entry in feed.entries:
# Create the database row
article = Article(entry)
# If the row already exists in the database
if db.session.query(Article).filter_by(uuid=article.uuid).first():
print "duplicate"
else:
db.session.merge(article)
db.session.commit()
当文章已经存在于数据库中时,它会被忽略。但是,如果它存在于 Session 中但尚未提交数据库,那么 SQLAlchemy 会尝试在同一个事务中多次写入它,我得到sqlalchemy.exc.IntegrityError: (IntegrityError) column hash is not unique。
我的直觉是我需要检查会话中是否不存在具有该哈希的对象(以及查询数据库),我认为这就是合并会做的,但我仍然得到错误。
【问题讨论】:
-
你试过了吗:
if article in db.session or db.session.query(Article).filter_by(uuid=article.uuid).first():? (刚刚在文档中找到它:docs.sqlalchemy.org/en/rel_0_9/orm/… 它可能根本不起作用)
标签: python flask sqlalchemy